Time Limit: 4000MS | Memory Limit: 65536K | |
Total Submissions: 25216 | Accepted: 6882 |
Description
Input
Output
Sample Input
2 2 1 2 5 2 1 4 1 2 2
Sample Output
14
这题就是求K短路,裸的模板题~~~
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cstring> 5 #include <queue> 6 using namespace std; 7 8 const int MAXN=1010,MAXM=100010; 9 int cnt,fir[MAXN],nxt[MAXM],to[MAXM],val[MAXM]; 10 int rcnt,rfir[MAXN],rnxt[MAXM],rto[MAXM],rval[MAXM]; 11 int dis[MAXN]; 12 struct A{ 13 int f,g,dot; 14 bool operator <(const A a)const{ 15 return a.f<f; 16 } 17 }; 18 19 void raddedge(int a,int b,int v) 20 { 21 rnxt[++rcnt]=rfir[a];rto[rcnt]=b;rfir[a]=rcnt;rval[rcnt]=v; 22 } 23 24 void addedge(int a,int b,int v) 25 { 26 nxt[++cnt]=fir[a];to[cnt]=b;fir[a]=cnt;val[cnt]=v; 27 raddedge(b,a,v); 28 } 29 int vis[MAXN]; 30 void Spfa(int src) 31 { 32 queue<int>q; 33 memset(dis,127,sizeof(dis)); 34 memset(vis,0,sizeof(vis)); 35 dis[src]=0;vis[src]=1;q.push(src); 36 while(!q.empty()) 37 { 38 int node=q.front();q.pop();vis[node]=0; 39 for(int i=rfir[node];i;i=rnxt[i]) 40 if(dis[rto[i]]>dis[node]+rval[i]){ 41 dis[rto[i]]=dis[node]+rval[i]; 42 if(!vis[rto[i]]) 43 q.push(rto[i]); 44 vis[rto[i]]=1; 45 } 46 } 47 } 48 49 int Astar(int s,int t,int k) 50 { 51 int cont=0; 52 priority_queue<A>Q; 53 if(dis[s]==dis[0])return -1; 54 if(s==t)k++; 55 Q.push((A){dis[s],0,s}); 56 A node; 57 while(!Q.empty()) 58 { 59 node=Q.top();Q.pop(); 60 if(node.dot==t&&++cont==k) 61 return node.f; 62 for(int i=fir[node.dot];i;i=nxt[i]) 63 Q.push((A){dis[to[i]]+node.g+val[i],node.g+val[i],to[i]}); 64 } 65 return -1; 66 } 67 68 void Init() 69 { 70 cnt=rcnt=0; 71 memset(fir,0,sizeof(fir)); 72 memset(rfir,0,sizeof(rfir)); 73 } 74 int main() 75 { 76 int x,y,k,n,m,v,s,t; 77 while(~scanf("%d%d",&n,&m)){ 78 Init(); 79 for(int i=1;i<=m;i++){ 80 scanf("%d%d%d",&x,&y,&v); 81 addedge(x,y,v); 82 } 83 scanf("%d%d%d",&s,&t,&k); 84 Spfa(t); 85 printf("%d\n",Astar(s,t,k)); 86 } 87 return 0; 88 }
图论(A*算法,K短路) :POJ 2449 Remmarguts' Date
原文:http://www.cnblogs.com/TenderRun/p/5215329.html