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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu1598 find the most comfortable road 枚举+最小生成树相关的知识,希望对你有一定的参考价值。

 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 枚举+最小生成树的主要内容,如果未能解决你的问题,请参考以下文章

hdu1598 find the most comfortable road (枚举)+并查集

HDU 1598 find the most comfortable road(最小生成树)

HDU 3640I, zombie (二分)

hdu 1599 find the mincost route

HDU_3193_Find the hotel

[HDU1599]find the mincost route