Description
Input
Output
Sample Input
2 2 1 2 5 2 1 4 1 2 2
Sample Output
14
分析:求s点到t点的第k短路的长度,注意s==t的情况,if(s==t) k++;不需要多考虑,直接上k短路的模板(SPFA+A*)
AC代码:
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 #define INF 0xfffffff 7 typedef struct 8 { 9 int to,w,next; 10 }Node; 11 Node edge[100000]; 12 typedef struct 13 { 14 int to,w,next; 15 }Node1; 16 Node1 edge1[100000]; 17 struct NODE 18 { 19 int to,f,g; 20 bool operator < (const NODE &r) const{ 21 if(f==r.f) return g>r.g; 22 return f>r.f; 23 } 24 }; 25 int n,m,s,t,k,ans; 26 int first[1001],first1[1001],q[10000],vis[1001],dist[1001]; 27 void SPFA(int s,int t) 28 { 29 int i,j,top,front,rear; 30 for(i=1;i<=n;i++) 31 dist[i]=INF; 32 memset(vis,0,sizeof(vis)); 33 dist[s]=0; 34 vis[s]=1; 35 front=rear=0; 36 q[rear++]=s; 37 while(front<rear) 38 { 39 top=q[front++]; 40 vis[top]=0; 41 for(i=first1[top];i!=-1;i=edge1[i].next) 42 { 43 j=edge1[i].to; 44 if(dist[j]>dist[top]+edge1[i].w) 45 { 46 dist[j]=dist[top]+edge1[i].w; 47 if(!vis[j]) 48 { 49 vis[j]=1; 50 q[rear++]=j; 51 } 52 } 53 } 54 } 55 } 56 int A_star() 57 { 58 int i,cnt; 59 NODE e,ne; 60 priority_queue<NODE> que; 61 if(s==t) 62 k++; 63 if(dist[s]==INF) 64 return -1; 65 cnt=0; 66 e.to=s; 67 e.g=0; 68 e.f=e.g+dist[e.to]; 69 que.push(e); 70 while(!que.empty()) 71 { 72 e=que.top(); 73 que.pop(); 74 if(e.to==t) 75 cnt++; 76 if(cnt==k) 77 return e.g; 78 for(i=first[e.to];i!=-1;i=edge[i].next) 79 { 80 ne.to=edge[i].to; 81 ne.g=e.g+edge[i].w; 82 ne.f=ne.g+dist[ne.to]; 83 que.push(ne); 84 } 85 } 86 return -1; 87 } 88 int main() 89 { 90 int u,v,w,i,g; 91 while(scanf("%d%d",&n,&m)!=EOF) 92 { 93 memset(first,-1,sizeof(first)); 94 memset(first1,-1,sizeof(first1)); 95 g=0; 96 for(i=0;i<m;i++) 97 { 98 scanf("%d%d%d",&u,&v,&w); 99 edge[g].to=v; 100 edge[g].w=w; 101 edge[g].next=first[u]; 102 first[u]=g; 103 edge1[g].to=u; 104 edge1[g].w=w; 105 edge1[g].next=first1[v]; 106 first1[v]=g++; 107 } 108 scanf("%d%d%d",&s,&t,&k); 109 SPFA(t,s); 110 ans=A_star(); 111 printf("%d\n",ans); 112 } 113 return 0; 114 }