-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP10600.cpp
executable file
·101 lines (92 loc) · 2.02 KB
/
P10600.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
94
95
96
97
98
99
100
101
typedef pair<int,PI> Edge;
int find(int x, int *parents) {
if(parents[x] != x)
parents[x] = find(parents[x], parents);
return parents[x];
}
bool _union(int x, int y, int *parents, int *ranks, bool skip) {
int xRoot = find(x, parents);
int yRoot = find(y, parents);
if(xRoot == yRoot)
return false;
if(skip)
return true;
// x and y are not already in same set. Merge them.
if(ranks[xRoot] < ranks[yRoot])
parents[xRoot] = yRoot;
else if(ranks[xRoot] > ranks[yRoot])
parents[yRoot] = xRoot;
else {
parents[yRoot] = xRoot;
++ranks[xRoot];
}
return true;
}
int main() {
int N, M, a, b, c;
int parents[100];
int ranks[100];
FORCAS {
// Read data:
cin >> N >> M;
vector<Edge> edges;
FORI(M) {
cin >> a >> b >> c; --a; --b;
edges.push_back(Edge(c, PI(a,b)));
}
sort(edges.begin(), edges.end());
// Prepare Union-find structure (parents and ranks):
FORI(N) {
ranks[i] = 0;
parents[i] = i;
}
// Compute minimal price:
int cost = 0;
int size = 0;
FORI(M) {
Edge &e = edges[i];
PI p = e.second;
if(_union(p.P1, p.P2, parents, ranks, false)) {
cost += e.first;
++size;
if(size == N-1)
break;
}
}
// Output cheapest plan:
cout << cost << " ";
// Find maximum flow path between S and D:
int min = 2000000000;
for(int skip = 0; skip < N-1; ++skip) {
size = 0;
int m = 0; // new cost
// Prepare Union-find structure (parents and ranks):
FORI(N) {
ranks[i] = 0;
parents[i] = i;
}
// Run:
FORI(M) {
Edge &e = edges[i];
PI p = e.second;
if(_union(p.P1, p.P2, parents, ranks, skip == size)) {
if(skip != size) {
m += e.first; // Only count edge when actually added.
}
++size;
if(size == N)
break;
}
}
//cerr << "Run " << skip << ": " << m << endl;
if(size == N && m < min) {
min = m;
if(min == cost)
break;
}
}
if(2000000000 == min)
die();
cout << min << endl;
}
}