-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuva-10600.cpp
93 lines (79 loc) · 1.96 KB
/
uva-10600.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//uva 10600
//ACM contest and Blackout
#include <iostream>
#include <algorithm>
#include <climits>
#include <vector>
#include <set>
using namespace std;
int findParent(vector <int> & ufds, int x);
void _union(vector <int> & ufds, int x, int y);
int Kruskal(set < pair <int, pair <int, int> > > Edges, set < pair <int, pair <int, int> > > & Unused, vector <int> & ufds);
int main(void)
{
int T;
cin >> T;
while(T--){
int n, m;
cin >> n >> m;
set < pair <int, pair <int, int> > > Edges;
for(int i = 0; i < m; ++i){
int u, v, cost;
cin >> u >> v >> cost;
--u, --v;
Edges.insert(make_pair(cost, make_pair(u, v)));
}
set < pair <int, pair <int, int> > > Unused;
vector <int> ufds(n, -1);
int firstMinCost = Kruskal(Edges, Unused, ufds);
int secondMinCost = INT_MAX;
for(auto a : Unused){
int cost = a.first;
int u = a.second.first;
int v = a.second.second;
std::fill(ufds.begin(), ufds.end(), -1);
set < pair <int, pair <int, int> > > tmp;
_union(ufds, u, v);
cost += Kruskal(Edges, tmp, ufds);
secondMinCost = min(secondMinCost, cost);
}
cout << firstMinCost << ' ' << secondMinCost << endl;
}
return 0;
}
int Kruskal(set < pair <int, pair <int, int> > > Edges, set < pair <int, pair <int, int> > > & Unused, vector <int> & ufds)
{
int result = 0;
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);
result += cost;
}
else
Unused.insert(make_pair(cost, make_pair(u, v)));
}
return result;
}
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[p2] = p1;
return;
}