标签:
Time Limit: 4000MS | Memory Limit: 65536K | |
Total Submissions: 27699 | Accepted: 7500 |
Description
Input
Output
Sample Input
2 2 1 2 5 2 1 4 1 2 2
Sample Output
14
Source
题解:
k短路模板
AC代码:
#include<cstdio> #include<queue> using namespace std; const int N=50010; struct node{ int v,next; int w; }e1[N*10],e2[N*10]; int tot,n,m,k,head1[N],head2[N]; int dis[N]; bool vis[N]; struct data{ int f,g; int from; data(int x,double y,double z):from(x),f(y),g(z){} bool operator < (const data &a) const { if(f==a.f) return g>a.g; return f>a.f; } }; inline void read(int &x){ register char ch=getchar();x=0; while(ch>‘9‘||ch<‘0‘) ch=getchar(); while(ch>=‘0‘&&ch<=‘9‘) x=(x<<3)+(x<<1)+ch-‘0‘,ch=getchar(); } void add(int x,int y,int z){ ++tot; e1[tot].v=y;e1[tot].w=z;e1[tot].next=head1[x];head1[x]=tot; e2[tot].v=x;e2[tot].w=z;e2[tot].next=head2[y];head2[y]=tot; } void spfa(int S){ for(int i=1;i<=n;i++) dis[i]=0x3f3f3f3f; dis[S]=0; queue<int>q; q.push(S); vis[S]=1; while(!q.empty()){ int h=q.front();q.pop(); vis[h]=0; for(int i=head2[h];i;i=e2[i].next){ int v=e2[i].v,w=e2[i].w; if(dis[v]>dis[h]+w){ dis[v]=dis[h]+w; if(!vis[v]){ vis[v]=1; q.push(v); } } } } } void a_star(int S,int T){ priority_queue<data>q; if(S==T) k++; int cnt=0; q.push(data(S,dis[S],0)); while(!q.empty()){ data h=q.top();q.pop(); if(h.from==T){ if(++cnt==k){ printf("%d",h.f); return ; } } for(int i=head1[h.from];i;i=e1[i].next){ q.push(data(e1[i].v,h.g+e1[i].w+dis[e1[i].v],h.g+e1[i].w));//最短路更新k短路 } } puts("-1"); } int main(){ int x,y,z,S,T; read(n);read(m); for(int i=1;i<=m;i++){ read(x);read(y);read(z); add(x,y,z); } read(S);read(T);read(k); spfa(T); a_star(S,T); return 0; }
标签:
原文地址:http://www.cnblogs.com/shenben/p/5880307.html