-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuva-10842.cpp
79 lines (65 loc) · 1.56 KB
/
uva-10842.cpp
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
//uva 10842
//Traffic Flow
#include <iostream>
#include <climits>
#include <vector>
#include <set>
using namespace std;
int kruskal(int n, set < pair <int, pair <int, int> >, greater <pair <int, pair <int, int> > > > & Edges);
void _union(vector <int> & ufds, int x, int y);
int findParent(vector <int> & ufds, int x);
int main(void)
{
int T, tcounter = 0;
cin >> T;
while(T--){
++tcounter;
int n, m;
cin >> n >> m;
set < pair <int, pair <int, int> >, greater <pair <int, pair <int, int> > > > Edges;
for(int i = 0; i < m; ++i){
int u, v, cost;
cin >> u >> v >> cost;
Edges.insert(make_pair(cost, make_pair(u, v)));
}
int result = kruskal(n, Edges);
cout << "Case #" << tcounter << ": ";
cout << result << endl;
}
return 0;
}
int kruskal(int n, set < pair <int, pair <int, int> >, greater <pair <int, pair <int, int> > > > & Edges)
{
vector <int> ufds(n, -1);
int maxEdgeInTree = INT_MAX;
while(!Edges.empty()){
int cost = Edges.begin()->first;
int u = Edges.begin()->second.first;
int v = Edges.begin()->second.second;
Edges.erase(Edges.begin());
if(findParent(ufds, u) != findParent(ufds, v)){
_union(ufds, u, v);
maxEdgeInTree = min(maxEdgeInTree, cost);
}
}
return maxEdgeInTree;
}
int findParent(vector <int> & ufds, int x)
{
int root = x;
while(ufds[root] != -1)
root = ufds[root];
while(ufds[x] != -1){
int next = ufds[x];
ufds[x] = root;
x = next;
}
return root;
}
void _union(vector <int> & ufds, int x, int y)
{
int p1 = findParent(ufds, x);
int p2 = findParent(ufds, y);
ufds[p1] = p2;
return;
}