There are n villages, all separate at first. Roads are built one at a time, each joining two villages. After every road, report how many groups of connected villages there are and how large the largest group is.
What to build
Use union-find with a size array. Start with n groups and largest size 1. For each road, unite the two villages; when they were in different groups, subtract 1 from the group count and update the largest size with the new group's size.
Requirements
- Print
GROUPS LARGESTafter every road - Use union by size and path compression
Input
The first line has n and m. Each of the next m lines has two villages a b.
Output
m lines, each GROUPS LARGEST, one after each road.
Constraints
1 ≤ n, m ≤ 100,000.
Example
Input:
5 4
1 2
3 4
2 1
2 3
Output:
4 2
3 2
3 2
2 4
Why it works
A road merges two groups only when the roots differ, and then the group count falls by exactly one. The new group's size is the sum of the two, which is stored at the new root, so the largest size can be updated in O(1).
Examples
5 4 1 2 3 4 2 1 2 3
4 2 3 2 3 2 2 4
3 1 1 1
3 1
Hints
Hint 1
If find(a) == find(b) nothing changes; print the same numbers again.
Hint 2
After attaching b's root under a's root, sz[a] is the new group size; update largest = max(largest, sz[a]).
Hint 3
Use a function that returns whether it merged, or compare roots in main.
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;
int groups = n, largest = 1;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a = find(a);
b = find(b);
if (a != b) {
if (sz[a] < sz[b]) swap(a, b);
parent[b] = a;
sz[a] += sz[b];
groups--;
largest = max(largest, sz[a]);
}
cout << groups << " " << largest << "\n";
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step