All problems

Problem 634

Number of Islands II

Hard · 30 pts · Matrix, Union Find

Problem

An R × C grid starts as all water. Q operations each turn the cell (row, column) into land; a cell may be chosen more than once, in which case nothing changes. After each operation, print the number of islands, where an island is a group of land cells connected horizontally or vertically. Use union-find: a new land cell starts as its own island, and every union with a neighbouring land cell of a different island merges two islands into one.

Input

The first line contains R, C and Q. Each of the next Q lines contains a row and a column (counted from 0).

Output

Print Q integers separated by spaces: the number of islands after each operation.

Constraints

1 <= R, C <= 10000; R × C <= 100000; 1 <= Q <= 100000

Example input

3 3 4
0 0
0 1
1 2
2 1

Example output

1 1 2 3

Explanation

In a 3 × 3 grid, adding (0,0) makes 1 island, adding (0,1) joins it, adding (1,2) creates a second island, and adding (2,1) creates a third. So the counts are 1 1 2 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Height Trees Next: Word Search II