poj 2449 Remmarguts' Date 第K短路
Posted 晓风微微
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 2449 Remmarguts' Date 第K短路相关的知识,希望对你有一定的参考价值。
题意:求T到S的第K短路
做法:
SPFA+A*
我们将各个点到终点的距离+这个点已走过的距离为启发式函数
在终点第K次入队时,此距离为第k短路。
坑点:
1.起点终点一样,一开始不算做到达,只有出去再回来才算做到达,因为这个WA了好久。
2.用SPFA求各个点到终点的最短距离时,没有将图上的边反向,导致MLE
代码:
1 //第k短路,自写,有向图,A*+SPFA 2 #include<iostream> 3 using namespace std; 4 #include<cstring> 5 #include<vector> 6 #include<queue> 7 #include<cstdio> 8 #define MAXN 1200 9 int n,m,s,t,k; 10 int d[MAXN]; 11 int cs[MAXN]; 12 struct teamdata{ 13 int dist; 14 int point; 15 bool operator<(const teamdata&b)const{ 16 return this->dist+d[this->point]>b.dist+d[b.point]; 17 } 18 }; 19 struct bian{ 20 int val; 21 int point; 22 }; 23 vector<bian> maps[MAXN]; 24 vector<bian> maps2[MAXN]; 25 int zd[MAXN]; 26 void SPFA(int s){ 27 queue<teamdata> team; 28 while(!team.empty()) team.pop(); 29 for (int i=0;i<=n;i++) zd[i]=0x7ffffff; 30 teamdata pt;pt.dist=0;pt.point=s; 31 zd[s]=0; 32 team.push(pt);teamdata pd; 33 while(!team.empty()){ 34 pt=team.front();team.pop(); 35 int point=pt.point;int distp=pt.dist; 36 for (int i=0;i<maps2[point].size();i++){ 37 int nd=maps2[point][i].point; 38 if (zd[nd]>(distp+maps2[point][i].val)){ 39 zd[nd]=distp+maps2[point][i].val; 40 pd.dist=zd[nd];pd.point=nd; 41 team.push(pd); 42 } 43 } 44 } 45 for (int i=0;i<=n;i++) d[i]=zd[i]; 46 } 47 int short_k(int s,int t,int k){ 48 priority_queue<teamdata> priteam; 49 memset(cs,0,sizeof(cs)); 50 while(!priteam.empty()) priteam.pop(); 51 teamdata pt,pd; 52 pt.dist=0;pt.point=s;priteam.push(pt); 53 int ans=-1; 54 if (d[s]==-1) return -1; 55 while(!priteam.empty()){ 56 pt=priteam.top();priteam.pop(); 57 cs[pt.point]++; 58 // cout<<pt.point<<" "<<cs[pt.point]<<" "<<pt.dist<<endl; 59 if (pt.point==t&&cs[pt.point]==k){ 60 ans=pt.dist;break; 61 } 62 for (int i=0;i<maps[pt.point].size();i++){ 63 pd.dist=pt.dist+maps[pt.point][i].val; 64 pd.point=maps[pt.point][i].point; 65 priteam.push(pd); 66 } 67 } 68 return ans; 69 } 70 int main(){ 71 while(scanf("%d%d",&n,&m)!=EOF){ 72 for (int i=0;i<=1010;i++) d[i]=0x7fffffff,maps[i].clear(),maps2[i].clear(); 73 bian pt; 74 for (int i=0;i<m;i++){ 75 int p,q;int w; 76 scanf("%d%d%d",&p,&q,&w); 77 pt.point=q;pt.val=w; 78 maps[p].push_back(pt); 79 pt.point=p;pt.val=w; 80 maps2[q].push_back(pt); 81 } 82 scanf("%d%d%d",&s,&t,&k); 83 if(s==t) k++; 84 SPFA(t); 85 // cout<<"OK"<<endl; 86 int ans=short_k(s,t,k); 87 printf("%d\n",ans); 88 } 89 return 0; 90 }
以上是关于poj 2449 Remmarguts' Date 第K短路的主要内容,如果未能解决你的问题,请参考以下文章