poj 2485 Highways

用kruskal()算法处理》》。

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define MAXN 300000
 4 
 5 int T, n, h, u[MAXN], v[MAXN], w[MAXN], p[510], r[MAXN];
 6 
 7 int cmp(const void *_p, const void *_q)
 8 {
 9     int *p = (int *)_p;
10     int *q = (int *)_q;
11     return w[*p] - w[*q];
12 }
13 
14 int find(int x){return p[x] == x ? x : p[x] = find(p[x]);}
15 
16 void kruskal()
17 {
18     int ans = 0;
19     for(int i = 0; i < n; i ++) p[i] = i;
20     for(int i = 0; i < h; i ++) r[i] = i;
21     qsort(r,h,sizeof(r[0]),cmp);
22     for(int i = 0; i < h; i ++)
23     {
24         int e = r[i], x = find(u[e]), y = find(v[e]);
25         if(x != y){ans = w[e]; p[x] = y;}
26     }
27     printf("%d\n",ans);
28 }
29 
30 int main()
31 {
32     while(~scanf("%d",&T))
33     {
34         while(T--)
35         {
36             scanf("%d",&n);
37             h = 0;
38             for(int i = 0; i < n; i ++)
39             {
40                 for(int j = 0; j < n; j ++)
41                 {
42                     int a;
43                     scanf("%d",&a);
44                     if(i == j) continue;
45                     u[h] = i, v[h] = j, w[h++] = a;
46                 }
47             }
48             kruskal();
49         }
50     }    
51 }
posted on 2012-08-04 11:11  BFP  阅读(124)  评论(0编辑  收藏  举报