标签:style blog http color io os ar for sp
1 //Accepted 188 KB 32 ms 2 //spfa 最短路 3 //每个intersection到第一个连接点是不要switch的 4 //到其他的intersection要switch一次 5 #include <cstdio> 6 #include <cstring> 7 #include <iostream> 8 #include <queue> 9 #include <cmath> 10 #include <algorithm> 11 using namespace std; 12 /** 13 * This is a documentation comment block 14 * 如果有一天你坚持不下去了,就想想你为什么走到这儿! 15 * @authr songt 16 */ 17 const int imax_n = 105; 18 const int inf = 100000000; 19 int a[imax_n][imax_n]; 20 bool vis[imax_n]; 21 int dis[imax_n]; 22 int n; 23 bool relax(int u,int v,int c) 24 { 25 if (dis[v]>dis[u]+c) 26 { 27 dis[v]=dis[u]+c; 28 return true; 29 } 30 return false; 31 } 32 queue<int > Q; 33 void spfa(int src) 34 { 35 while (!Q.empty()) Q.pop(); 36 memset(vis,0,sizeof(vis)); 37 for (int i=1;i<=n;i++) 38 dis[i]=inf; 39 dis[src]=0; 40 Q.push(src); 41 vis[src]=true; 42 while (!Q.empty()) 43 { 44 int pre=Q.front(); 45 Q.pop(); 46 vis[pre]=false; 47 for (int i=1;i<=n;i++) 48 if (relax(pre,i,a[pre][i]) && !vis[i]) 49 { 50 Q.push(i); 51 vis[i]=true; 52 } 53 } 54 } 55 int start,end; 56 int main() 57 { 58 int x,y,cnt; 59 while (scanf("%d%d%d",&n,&start,&end)!=EOF) 60 { 61 for (int i=1;i<=n;i++) 62 { 63 for (int j=1;j<=n;j++) 64 a[i][j]=inf; 65 a[i][i]=0; 66 } 67 for (int i=1;i<=n;i++) 68 { 69 scanf("%d",&cnt); 70 if (cnt!=0) 71 { 72 scanf("%d",&x); 73 a[i][x]=0; 74 cnt--; 75 } 76 for (int j=0;j<cnt;j++) 77 { 78 scanf("%d",&x); 79 a[i][x]=1; 80 } 81 } 82 //printf("gg\n"); 83 spfa(start); 84 if (start==end) dis[end]=1; 85 if (dis[end]==inf) printf("-1\n"); 86 else 87 printf("%d\n",dis[end]); 88 } 89 return 0; 90 }
标签:style blog http color io os ar for sp
原文地址:http://www.cnblogs.com/djingjing/p/4033510.html