标签:int directed contains emma scanf develop cap rip nta
Description
Input
Output
Sample Input
2 2 1 2 5 2 1 4 1 2 2
Sample Output
14
题解
题目就是一道裸的第k短路。。。
dij中做A*
该点到终点最小距离作为估价函数,dij的时候每次挑最小的f=g+h出来拓展,g就是起点到该点的最小距离。
要注意一下,如果终点和起点相同,那么k++,因为距离为0不算是最短的路。
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 #define maxn 1005 7 #define maxm 100005 8 #define inf 1<<29 9 int s,t,k,n,cnt[maxn]; 10 int head[maxn],ecnt,headc[maxn],vis[maxn],d[maxn]; 11 struct edge{ 12 int u,v,next,w; 13 }E[maxm],Ec[maxm]; 14 struct Node{ 15 int g,v,f; 16 Node(int x,int y,int z):f(x),g(y),v(z){} 17 bool operator < (const Node& a) const{return a.f<f;} 18 }; 19 void addedge(int u,int v,int w) 20 { 21 E[++ecnt].u=u; 22 E[ecnt].v=v; 23 E[ecnt].w=w; 24 E[ecnt].next=head[u]; 25 head[u]=ecnt; 26 27 Ec[ecnt].u=v; 28 Ec[ecnt].v=u; 29 Ec[ecnt].w=w; 30 Ec[ecnt].next=headc[v]; 31 headc[v]=ecnt; 32 } 33 void spfa(int x) 34 { 35 queue<int> q; 36 for(int i=1 ; i<=n ; ++i) 37 d[i]=inf; 38 d[x]=0; 39 vis[x]=1; 40 q.push(x); 41 while(!q.empty()) 42 { 43 int dd=q.front();q.pop(); 44 vis[dd]=0; 45 for(int i=headc[dd] ; i ; i=Ec[i].next ) 46 { 47 int v=Ec[i].v; 48 int val=Ec[i].w; 49 if(d[v]>d[dd]+val) 50 { 51 d[v]=d[dd]+val; 52 if(!vis[v]) 53 { 54 vis[v]=1; 55 q.push(v); 56 } 57 } 58 } 59 } 60 } 61 int A_star(int x) 62 { 63 if(d[x]==inf)return -1; 64 if(s==t)k++; 65 priority_queue<Node> que; 66 que.push(Node(d[x],0,x)); 67 Node next(0,0,0); 68 while(!que.empty()) 69 { 70 Node now=que.top();que.pop(); 71 int dd=now.v; 72 cnt[dd]++; 73 if(cnt[t]==k)return now.g ; 74 if(cnt[dd]>k)continue; 75 for(int i=head[dd] ; i ; i=E[i].next ) 76 { 77 if(d[E[i].v]==inf)continue; 78 next.v=E[i].v; 79 next.g=now.g+E[i].w; 80 next.f=d[next.v]+next.g; 81 que.push(next); 82 } 83 } 84 return -1; 85 } 86 int main() 87 { 88 int m,u,v,w; 89 scanf("%d%d",&n,&m); 90 for(int i=1 ; i<=m ; ++i ) 91 { 92 scanf("%d%d%d",&u,&v,&w); 93 addedge(u,v,w); 94 } 95 scanf("%d%d%d",&s,&t,&k); 96 spfa(t); 97 printf("%d",A_star(s)); 98 return 0; 99 }
标签:int directed contains emma scanf develop cap rip nta
原文地址:http://www.cnblogs.com/fujudge/p/7496766.html