Description
Input
Output
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 <stdio.h> #include <string.h> #include <queue> #include <algorithm> 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<int> 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<node> 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<m; i++) { scanf("%d%d%d",&x,&y,&w); AddEdges(x,y,w,i); } scanf("%d%d%d",&s,&t,&k); SPFA(t); printf("%d\n",Astar(s,t)); } return 0; }
POJ2499:Remmarguts' Date(第K短路 SPFA+A*),布布扣,bubuko.com
POJ2499:Remmarguts' Date(第K短路 SPFA+A*)
原文:http://blog.csdn.net/libin56842/article/details/23632249