http://acm.hdu.edu.cn/showproblem.php?pid=2377
对所有公交车站点求最短路
View Code
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #include <algorithm> 5 using namespace std; 6 7 const int N=10010,M=200010; 8 struct edge 9 { 10 int v,w,next; 11 }e[M]; 12 int head[N],n,m,t; 13 bool inq[N]; 14 int dis[N],maxd[N],id[N]; 15 queue<int> q; 16 void addedge(int u,int v,int w) 17 { 18 edge et={v,w,head[u]}; 19 e[m]=et; 20 head[u]=m++; 21 } 22 void graphinit() 23 { 24 m=0; 25 memset(head,-1,sizeof(head)); 26 } 27 void read_graph() 28 { 29 graphinit(); 30 scanf("%d%d",&n,&t); 31 for(int i=0;i<n;i++) 32 { 33 int u,c,v; 34 scanf("%d%d",&u,&c); 35 id[i]=u; 36 while(c--) 37 { 38 scanf("%d",&v); 39 addedge(u,v,1); 40 } 41 } 42 } 43 void spfa(int p) 44 { 45 while(!q.empty()) q.pop(); 46 memset(inq,0,sizeof(inq)); 47 memset(dis,-1,sizeof(dis)); 48 dis[p]=0; 49 q.push(p); 50 while(!q.empty()) 51 { 52 int u=q.front(); q.pop(); 53 inq[u]=false; 54 for(int i=head[u];i!=-1;i=e[i].next) 55 { 56 int v=e[i].v, w=e[i].w; 57 if(dis[v]==-1 || dis[v]>dis[u]+w) 58 { 59 dis[v]=dis[u]+w; 60 if(!inq[v]) {inq[v]=true; q.push(v);} 61 } 62 } 63 } 64 } 65 int main() 66 { 67 int T; 68 scanf("%d",&T); 69 while(T--) 70 { 71 memset(maxd,0,sizeof(maxd)); 72 read_graph(); 73 while(t--) 74 { 75 int c; 76 scanf("%d",&c); 77 while(c--) 78 { 79 int x; 80 scanf("%d",&x); 81 spfa(x); 82 for(int i=0;i<n;i++) 83 if(dis[id[i]]>maxd[id[i]]) maxd[id[i]]=dis[id[i]]; 84 } 85 } 86 int ans=-1,u; 87 sort(id,id+n); 88 for(int i=0;i<n;i++) 89 if(ans==-1 || maxd[id[i]]<ans) {ans=maxd[id[i]]; u=id[i];} 90 printf("%d %d\n",ans+1,u); 91 } 92 return 0; 93 }