题目大意是给你几组数据,表示每个人之间的信息传递的时间,要求所用时间最短的人的编号和所用的最短时间。
可以用图论中的Floyd算法,经过Floyd算法后在邻接矩阵当中的就有了每个人的信息传递时间及编号;
接下来要做的是从邻接矩阵中查找信息。
View Code
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 5 int cost[101][101],n; 6 void Floyd() 7 { 8 int i,j,k; 9 for(k=1; k<=n; k++) 10 for(i=1; i<=n; i++) 11 { 12 if(cost[i][k] != 0) 13 for(j=1; j<=n; j++) 14 { 15 if(cost[k][j] && i!=j) 16 { 17 if((cost[i][j]==0)||(cost[i][j]>cost[i][k]+cost[k][j])) 18 cost[i][j] = cost[i][k] + cost[k][j]; 19 } 20 21 } 22 } 23 } 24 25 int main() 26 { 27 int i, j, ntests, laber, time; 28 int min, flag,number,t; 29 30 while(scanf("%d",&n) && n) 31 { 32 memset(cost,0,sizeof(cost)); 33 for(i=1; i<=n; i++) 34 { 35 scanf("%d",&ntests); 36 for(j=1; j<=ntests; j++) 37 { 38 scanf("%d%d",&laber,&time); 39 cost[i][laber] = time; 40 } 41 } 42 Floyd(); 43 44 min = 30000;//从邻接矩阵中查找信息。 45 number = -1; 46 for(i=1; i<=n; i++) 47 { 48 t = 0; 49 for(j=1; j<=n; j++) //每次取同一行中的最大值 50 { 51 if(i!=j) 52 { 53 if(cost[i][j] > t) t = cost[i][j]; 54 else if(cost[i][j]==0) 55 { 56 t = 30000; 57 break; 58 } 59 } 60 } 61 if(min > t)//如果同一行中每个人都能传递到则记录i的位置,即为所求位置,此时间也符合要求 62 { 63 number = i; 64 min = t; 65 } 66 } 67 if(min < 30000) printf("%d %d\n",number,min); 68 else printf("disjoint\n"); 69 } 70 return 0; 71 } 72