Description
"Good man never makes girls wait or breaks an appointment!" said the mandarin duck father. Softly touching his little ducks' head, he told them a story.Input
The first line contains two integer numbers N and M (1 <= N <= 1000, 0 <= M <= 100000). Stations are numbered from 1 to N. Each of the following M lines contains three integer numbers A, B and T (1 <= A, B <= N, 1 <= T <= 100). It shows that there is a directed sideway from A-th station to B-th station with time T.Output
A single line consisting of a single integer number: the length (time required) to welcome Princess Uyuw using the K-th shortest path. If K-th shortest path does not exist, you should output "-1" (without quotes) instead.Sample Input
2 2 1 2 5 2 1 4 1 2 2
Sample Output
14
這道題是給出了一個圖,然後給出起點s與終點t與k,要求s到t的第k短路是多少
首先這肯定是一個最短路的問題,我們可以用SPFA算出t到其他所有點的最短路徑,然後使用A*去迭代搜索,一開始,把s到t的最短路先壓入隊列中,那麼就變成了以t為起點去遍歷,在第k次回到t點的時候所走過的路徑最短的值便是第k短路徑
#include#include #include #include using namespace std; const int L = 100005; const int inf = 1<<30; struct node { int now,g,f; bool operator <(const node a)const { if(a.f == f) return a.g < g; return a.f < f; } }; struct edges { int x,y,w,next; } e[L<<2],re[L<<2];//e是輸入給出的定向圖,re為其逆向圖,用於求t到其他所有點的最短路徑 int head[1005],dis[1005],vis[1005],n,m,k,s,t,rehead[1005]; void Init()//初始化 { memset(e,-1,sizeof(e)); memset(re,-1,sizeof(re)); for(int i = 0; i<=n; i++) { dis[i] = inf; vis[i] = 0; head[i] = -1; rehead[i] = -1; } } void AddEdges(int x,int y,int w,int k) { e[k].x = x,e[k].y = y,e[k].w = w,e[k].next = head[x],head[x] = k; re[k].x = y,re[k].y = x,re[k].w = w,re[k].next = rehead[y],rehead[y] = k; } int relax(int u,int v,int c) { if(dis[v]>dis[u]+c) { dis[v] = dis[u]+c; return 1; } return 0; } void SPFA(int src) { int i; dis[src] = 0; queue Q; Q.push(src); while(!Q.empty()) { int u,v; u = Q.front(); Q.pop(); vis[u] = 0; for(i = rehead[u]; i!=-1; i = re[i].next) { v = re[i].y; if(relax(u,v,re[i].w) && !vis[v]) { Q.push(v); vis[v] = 1; } } } } int Astar(int src,int to) { priority_queue Q; int i,cnt = 0; if(src == to) k++;//在起點與終點是同一點的情況下,k要+1 if(dis[src] == inf) return -1; node a,next; a.now = src; a.g = 0; a.f = dis[src]; Q.push(a); while(!Q.empty()) { a = Q.top(); Q.pop(); if(a.now == to) { cnt++; if(cnt == k) return a.g; } for(i = head[a.now]; i!=-1; i = e[i].next) { next = a; next.now = e[i].y; next.g = a.g+e[i].w; next.f = next.g+dis[next.now]; Q.push(next); } } return -1; } int main() { int i,j,x,y,w; while(~scanf("%d%d",&n,&m)) { Init(); for(i = 0; i