-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path143.cpp
More file actions
85 lines (77 loc) · 1.24 KB
/
Copy path143.cpp
File metadata and controls
85 lines (77 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
Edge(int s, int t, int w) {
from = s;
to = t;
weight = w;
}
int from, to, weight;
};
int n, m;
int father[200];
vector<Edge> edges;
int find(int i) {
int p = father[i];
while (p != father[p]) {
p = father[p];
}
return p;
}
bool join(int i, int j) {
int fi = find(i);
int fj = find(j);
if (fi != fj) {
father[fi] = fj;
return true;
}
else {
return false;
}
}
int span(int l) {
int cnt = 0;
for (int i=0;i<n;i++) {
father[i] = i;
}
for (int i=l;i<m;i++) {
if (join(edges[i].from, edges[i].to)){
cnt++;
}
if (cnt == n - 1){
return edges[i].weight - edges[l].weight;
}
}
return -1;
}
bool compare(const Edge& a, const Edge& b) {
return a.weight < b.weight;
}
int main() {
while (cin >> n >> m) {
if (n == 0) {
break;
}
edges.clear();
for (int i=0;i<m;i++) {
int s, t, w;
cin >> s >> t >> w;
s--;
t--;
Edge te(s, t, w);
edges.push_back(te);
}
sort(edges.begin(), edges.end(), compare);
int ans = 2147483647;
for (int i=0;i<m;i++) {
int result = span(i);
if (result >= 0 && result < ans) {
ans = result;
}
}
cout << (ans < 2147483647 ? ans : -1) << endl;
}
return 0;
}