Sicily 1504:Slim Span(最小生成树)

Posted Vincent_Bryan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sicily 1504:Slim Span(最小生成树)相关的知识,希望对你有一定的参考价值。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 struct Vertex{
 5     int start, end;
 6     int weight;
 7 };
 8 Vertex arr[10000];
 9 int par[10000];
10 int n, m;
11 int find(int n){
12     while(par[n] != n){
13         n = par[n];
14     }
15     return n;
16 }
17 void merge(int n1, int n2){
18     while(par[n1] != n1){
19         n1 = par[n1];
20         par[n1] = n2;
21     }
22     par[n1] = n2;
23 }
24 bool cmp(Vertex v1, Vertex v2){
25     return v1.weight < v2.weight;
26 }
27 
28 void init(){                       
29     for(int i = 0; i <= n; i++)par[i] = i;
30 }
31 
32 long long func(int k){
33     init();
34     int weight_max = 0;
35     int i = 0;
36     bool fail = false;
37     int kk = k;
38     while(i < n-1){
39         if(k >= m){
40             fail = true;
41             break;
42         }
43         Vertex tmp = arr[k++];
44         int n1 = find(tmp.start);
45         int n2 = find(tmp.end);
46         if(n1 == n2){
47             continue;
48         }
49         else{
50             if(i == n-2){
51                 weight_max = tmp.weight;
52             }
53             if(n1 > n2)swap(n1, n2);
54             merge(n2, n1);
55             i++;
56         }
57     }
58     
59     if(fail) return -1;
60     else return weight_max - arr[kk].weight;
61 }
62 
63 int main(){
64     while(scanf("%d%d", &n, &m) != EOF && (n != 0 || m != 0)){
65         init();
66         for(int i = 0; i < m; i++){
67             scanf("%d%d%d", &arr[i].start, &arr[i].end, &arr[i].weight);
68         }
69         int MIN = 100000000;
70         sort(arr, arr+m, cmp);
71         for(int i = 0; i < m; i++){
72             int tmp = func(i);
73             if(tmp != -1)MIN = min(MIN, tmp);
74         }
75         if(MIN == 100000000){
76             printf("-1\\n");
77         }
78         else{
79             printf("%d\\n", MIN);
80         }
81     }
82 } 

 

以上是关于Sicily 1504:Slim Span(最小生成树)的主要内容,如果未能解决你的问题,请参考以下文章

UVa 1395 Slim Span (最小生成树)

[2016-01-27][UVA][1395][D -?Slim Span]

POJ 3552 Slim Span (最小差值生成树)

Uva1395 POJ3522 Slim Span (最小生成树)

UVa 1395 - Slim Span(最小生成树变形)

UVA 1359 POJ 3522 Slim Span(最小生成树kruskal)