poj2449(第k短路)
生活随笔
收集整理的這篇文章主要介紹了
poj2449(第k短路)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
給出一個n個點、m條邊的有向有環圖,求從s到t的第k短路是多少。
思路:
spfa+A*。
代碼:
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<cmath> #include<queue>using namespace std;#define MAXN 1050 #define MAXM 500050 #define INF 123456789struct node {int v,w,next; }; node edge1[MAXM]; node edge2[MAXM];struct A {int f,g,v;bool operator < (const A a)const{if(a.f==f)return a.g<g;return a.f<f;} };int e,n,m,s,t,k; int vis[MAXN]; int d[MAXN]; int q[MAXM*5]; int head1[MAXN]; int head2[MAXN];void addedge(int x,int y,int w) {edge1[e].v=y;edge1[e].w=w;edge1[e].next=head1[x];head1[x]=e;edge2[e].v=x;edge2[e].w=w;edge2[e].next=head2[y];head2[y]=e++; }void spfa(int src) {for(int i=1; i<=n; i++)d[i]=INF;memset(vis,0,sizeof(vis));vis[src]=0;int h=0,t=1;q[0]=src;d[src]=0;while(h<t){int u=q[h++];vis[u]=0;for(int i=head2[u]; i!=-1; i=edge2[i].next){int v=edge2[i].v;int w=edge2[i].w;if(d[v]>d[u]+w){d[v]=d[u]+w;if(!vis[v]){q[t++]=v;vis[v]=1;}}}} }int Astar(int src,int des) {int cnt=0;priority_queue<A>Q;if(src==des)k++;if(d[src]==INF)return -1;A t,tt;t.v=src,t.g=0,t.f=t.g+d[src];Q.push(t);while(!Q.empty()){tt=Q.top();Q.pop();if(tt.v==des){cnt++;if(cnt==k)return tt.g;}for(int i=head1[tt.v]; i!=-1; i=edge1[i].next){t.v=edge1[i].v;t.g=tt.g+edge1[i].w;t.f=t.g+d[t.v];Q.push(t);}}return -1; }int main() {while(scanf("%d%d",&n,&m)!=EOF){e=0;memset(head1,-1,sizeof(head1));memset(head2,-1,sizeof(head2));for(int i=0; i<m; i++){int u,v,x;scanf("%d%d%d",&u,&v,&x);addedge(u,v,x);}scanf("%d%d%d",&s,&t,&k);spfa(t); // for(int i=1;i<=n;i++) // printf("dis=%d\n",d[i]);int ans=Astar(s,t);printf("%d\n",ans);}return 0; }總結
以上是生活随笔為你收集整理的poj2449(第k短路)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu5489(2015合肥网络赛F题)
- 下一篇: uvalive4744(数论)