Counting Islands After Each Bridge

easy ☼ daily · +1 ◆ union-find graphs 1000 ms · 256 MB

Counting Islands After Each Bridge

An archipelago consists of n islands numbered from 1 to n. At first there are no bridges, so every island is its own separate group.

Bridges are now built one at a time. The i-th bridge connects islands u_i and v_i and can be crossed in both directions. Two islands belong to the same group if you can walk from one to the other using bridges built so far.

A bridge may connect two islands that are already in the same group, the same pair of islands may get several bridges, and a bridge may even start and end on the same island (a scenic loop).

After each bridge is built, report the number of groups.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 1 ≤ m ≤ 2·10^5): the number of islands and the number of bridges.

Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n): the islands connected by the i-th bridge, in the order the bridges are built.

Output

Print m lines. The i-th line must contain the number of island groups right after the i-th bridge is built.

Notes

In the first example, the first bridge merges islands 1 and 2, leaving groups {1, 2}, {3}, {4}, {5}. The second bridge merges {3} and {4}. The third bridge connects 2 and 1, which are already together, so the count stays at 3. The fourth bridge joins {1, 2} with {3, 4}, and the last one is a loop on island 5, which changes nothing.

Example 1

Input

5 5
1 2
3 4
2 1
4 1
5 5

Output

4
3
3
2
2

Example 2

Input

6 7
1 2
3 4
5 6
2 3
4 1
6 4
3 3

Output

5
4
3
2
2
1
1

Hints · reveal one at a time if you're stuck

Hint 1

Start with n separate groups. A new bridge either joins two different groups or changes nothing. How can you quickly tell whether two islands are already connected while bridges keep being added?

Hint 2

Use a disjoint-set structure with path compression and union by size. Compare the roots of the two islands: only when they differ do you merge and reduce the count. Print the count after every bridge, including bridges that close a loop or repeat a connection.

report an issue Prefer your own editor? sooks prep 19 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.