chenxi16

导航

数据结构1 - 07-图4 哈利·波特的考试

 

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define MAXN 101 
 4 #define INF 0x3fffffff 
 5 
 6 int g[MAXN][MAXN],n,m,dist[MAXN],result[MAXN],vis[MAXN];
 7 void read();
 8 void Dijkstra(int s);
 9 int main(){
10     read();
11     int i,j,maxlen=INF,index=-1;
12     memset(result,0,sizeof(result));
13     for(i=1;i<=n;i++){
14         Dijkstra(i);
15         maxlen=0;
16         for(j=1;j<=n;j++){
17             if(dist[j]==INF) {
18                 result[i] = INF;
19                 break;
20             }
21             if(dist[j]>maxlen && dist[j]!=INF) maxlen = dist[j];
22         }
23         if(result[i]!=INF){
24             result[i] = maxlen;
25         }
26     }
27     maxlen = INF;
28     for(i=1;i<=n;i++){
29         if(result[i]!=INF && result[i]<maxlen ){
30             maxlen = result[i];
31             index = i;
32         }
33     }
34     if(index==-1) printf("0\n");
35     else printf("%d %d\n",index,maxlen);
36     return 0;
37 }
38 void read(){
39     scanf("%d %d",&n,&m);
40     int u,v,w,i,j;
41     for(i=1;i<=n;i++)
42       for(j=1;j<=n;j++)
43          g[i][j] = INF;
44     
45     for(i=1;i<=m;i++){
46         scanf("%d %d %d",&u,&v,&w);
47         g[u][v] = w;
48         g[v][u] = w;
49         
50     }
51 }
52 void Dijkstra(int s){
53     //fill(dist,dist+MAXN,INF);
54     //fill(vis,vis+MAXN,0);
55     for(int i=1;i<=n;i++)
56        dist[i] = INF;
57     for(int i=1;i<=n;i++)
58        vis[i] = 0;
59     int mdata,mindex,i;
60     dist[s] =0;
61     while(1){
62         mdata = INF;
63         mindex = -1;
64         for(i=1;i<=n;i++){
65             if(dist[i]<mdata&&vis[i]==0){
66                 mdata = dist[i];
67                 mindex = i;
68             }
69         }
70         if(mindex==-1) break;
71         vis[mindex] = 1;
72         for(i=1;i<=n;i++){
73             if(vis[i]==0&&g[mindex][i]!=INF&&mindex!=i){
74                 if(dist[mindex]+g[mindex][i]<dist[i]){
75                     dist[i] = dist[mindex] + g[mindex][i];
76                 }
77             }
78         }
79         
80     }
81 }
View Code

 

posted on 2020-04-05 17:43  chenxi16  阅读(184)  评论(0编辑  收藏  举报