码迷,mamicode.com
首页 > 其他好文 > 详细

hdu1598 find the most comfortable road 枚举+最小生成树

时间:2017-09-01 22:19:00      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:ons   min   use   最小生成树   style   most   nbsp   const   table   

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #define MAXN 210
 5 #define INF 2147483646
 6 using namespace std;
 7 
 8 int f[MAXN], Rank[MAXN];    //Rank长度
 9 int n, m, pos;
10 
11 struct Edge{
12     int u, v, val;
13     //按照val从小到大排列
14     friend bool operator<(const Edge&a, const Edge&b){
15         return a.val < b.val;
16     }
17 }arr[MAXN*MAXN];
18 
19 void init(){
20     for (int i = 0; i<MAXN; ++i)
21         f[i] = i, Rank[i] = 0;
22 }
23 
24 int find(int x){
25     int i, j = x;
26     while (j != f[j]) j = f[j];
27     while (x != j){
28         i = f[x]; f[x] = j; x = i;
29     }
30     return j;
31 }
32 
33 void Union(int x, int y){
34     int a = find(x), b = find(y);
35     if (a == b)return;
36     if (Rank[a]>Rank[b])
37         f[b] = a;
38     else{
39         if (Rank[a] == Rank[b])
40             ++Rank[b];
41         f[a] = b;
42     }
43 }
44 
45 int main(){
46     int u, v, speed, Q;
47     while (scanf("%d%d", &n, &m) != EOF){
48         for (int i = 0; i<m; ++i)
49             scanf("%d%d%d", &arr[i].u, &arr[i].v, &arr[i].val);
50         sort(arr, arr + m);
51         scanf("%d", &Q);
52         while (Q--){
53             scanf("%d%d", &u, &v);
54             int ans = INF;
55             for (int j = 0; j < m; ++j){
56                 init();
57                 for (int k = j; k < m; ++k){
58                     Union(arr[k].u, arr[k].v);
59                     if (find(u) == find(v)){
60                         ans = min(ans, arr[k].val - arr[j].val);    //使ans尽可能的小
61                         break;
62                     }
63                 }
64             }
65             if (ans == INF)
66                 printf("-1\n");
67             else 
68                 printf("%d\n", ans);
69         }
70     }
71     //system("pause");
72     return 0;
73 }

 

hdu1598 find the most comfortable road 枚举+最小生成树

标签:ons   min   use   最小生成树   style   most   nbsp   const   table   

原文地址:http://www.cnblogs.com/jaydenouyang/p/7465125.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!