A company wants to connect n offices with cables. Each possible cable joins two offices and has a cost. Find the cheapest set of cables that connects all the offices, or say it is impossible.
What to build
Use Kruskal's algorithm. Sort the cables by cost. Go through them; use union-find to add a cable only if its two offices are in different groups. If exactly n - 1 cables were added, print their total cost; otherwise print IMPOSSIBLE.
Requirements
- Sort the edges and use union-find
- Use
long longfor the total - Print
IMPOSSIBLEif the offices cannot all be connected
Input
The first line has n and m. Each of the next m lines has a b c: a possible cable between offices a and b costing c.
Output
The minimum total cost, or IMPOSSIBLE.
Constraints
1 ≤ n ≤ 100,000. 0 ≤ m ≤ 200,000. 1 ≤ c ≤ 10⁹.
Example
Input:
4 5
1 2 1
2 3 2
3 4 3
1 4 10
1 3 4
Output:
6
Why it works
Taking the cheapest edge that joins two different groups is always safe (the cut property of spanning trees), and an edge inside one group would only make a cycle. Union-find tells the two cases apart in almost constant time, so the sort dominates: O(m log m).
Examples
4 5 1 2 1 2 3 2 3 4 3 1 4 10 1 3 4
6
3 1 1 2 5
IMPOSSIBLE
Hints
Hint 1
Store each edge as a pair: pair<long long, pair<int, int> > e, then sort(edges.begin(), edges.end()). Sorting pairs sorts by cost first.
Hint 2
For each edge: if find(a) != find(b), unite, add the cost, and count the edge.
Hint 3
Check count == n - 1 at the end. For n = 1 the answer is 0.
Solution
Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<int> parent, sz;
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
int main() {
int n, m;
cin >> n >> m;
parent.resize(n + 1);
sz.assign(n + 1, 1);
for (int i = 0; i <= n; i++) parent[i] = i;
vector<pair<long long, pair<int, int> > > edges;
for (int i = 0; i < m; i++) {
int a, b;
long long c;
cin >> a >> b >> c;
edges.push_back(make_pair(c, make_pair(a, b)));
}
sort(edges.begin(), edges.end());
long long total = 0;
int used = 0;
for (size_t i = 0; i < edges.size(); i++) {
int a = find(edges[i].second.first), b = find(edges[i].second.second);
if (a == b) continue;
if (sz[a] < sz[b]) swap(a, b);
parent[b] = a;
sz[a] += sz[b];
total += edges[i].first;
used++;
}
if (used == n - 1) cout << total << "\n";
else cout << "IMPOSSIBLE\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step