Tram POJ - 1847 spfa
作者:互联网
#include<iostream> #include<algorithm> #include<queue> #include<cstdio> #include<cstring> using namespace std; const int N=1100,INF=0x3f3f3f3f; int h[N],e[N],v[N],w[N],ne[N],idx; int dist[N]; bool st[N]; int n,beg,en,ans; void add(int a,int b,int c) { v[idx]=a; e[idx]=b; w[idx]=c; ne[idx]=h[a]; h[a]=idx++; } void spfa(int sx) { queue<int>q; memset(dist,0x3f,sizeof dist); memset(st,0,sizeof st); st[sx]=1; q.push(sx); dist[sx]=0; while(q.size()) { int u=q.front(); q.pop(); st[u]=0; for(int i=h[u];i!=-1;i=ne[i]) { int j=e[i]; if(dist[j]>dist[u]+w[i]) { dist[j]=dist[u]+w[i]; if(!st[j]) { st[j]=1; q.push(j); } } } } if(dist[en]==INF) cout<<"-1"<<endl; else cout<<dist[en]<<endl; } void init() { ans=0; memset(h,-1,sizeof(h)); } void getmap() { int i,j; for(i=1;i<=n;i++) { int k; scanf("%d",&k); for(j=0;j<k;j++) { int a; scanf("%d",&a); if(j==0) add(i,a,0); else add(i,a,1); } } } int main() { while(~scanf("%d%d%d",&n,&beg,&en)) { init(); getmap(); spfa(beg); } return 0; }
标签:sx,dist,idx,Tram,1847,st,int,spfa,include 来源: https://www.cnblogs.com/QingyuYYYYY/p/12236327.html