Islands After Floods

HARD
G
Time limit: 3.0sMemory limit: 256MB
union-findgrid

Islands After Floods

You start with an all-water grid of r rows and c columns (0-indexed). One at a time, ​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌‌​​‌​​‌‌​‌‌​​‌‌​​​‌‌​‌‌​​‌​‌​​‌‌‌​​​​‌‌​​‌​​​‌‌​​​‌‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌‌​​​​​‌‌​​‌​​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌​‌‌​​​‌‌​‌​‌k cells turn into land (given as row col, and a cell may be listed more than once — a repeat has no effect). After each land placement, output the current number of distinct islands, where an island is a maximal group of land cells connected horizontally or vertically. ​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌‌​​‌​​‌‌​‌‌​​‌‌​​​‌‌​‌‌​​‌​‌​​‌‌‌​​​​‌‌​​‌​​​‌‌​​​‌‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌‌​​​​​‌‌​​‌​​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌​‌‌​​​‌‌​‌​‌

Input

Line 1: three integers r c k (1 ≤ r, c ≤ 1000, 1 ≤ k ≤ 2·10^4) Next k lines: two integers row col (0 ≤ row < r, 0 ≤ col < c)

Output

k lines: the number of islands after each placement.

Example

Input: ​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌‌​​‌​​‌‌​‌‌​​‌‌​​​‌‌​‌‌​​‌​‌​​‌‌‌​​​​‌‌​​‌​​​‌‌​​​‌‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌‌​​​​​‌‌​​‌​​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌​‌‌​​​‌‌​‌​‌``` 3 3 4 0 0 0 1 1 2 2 1

Output:

1 1 2 3


### Constraints
- 1 ≤ r, c ≤ 1000, 1 ≤ k ≤ 2·10^4
​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌‌​​‌​​‌‌​‌‌​​‌‌​​​‌‌​‌‌​​‌​‌​​‌‌‌​​​​‌‌​​‌​​​‌‌​​​‌‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌‌​​​​​‌‌​​‌​​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌​‌‌​​​‌‌​‌​‌

Sample Testcases

Case 1

Input
3 3 4
0 0
0 1
1 2
2 1
Expected Output
1
1
2
3

Case 2

Input
2 2 3
0 0
1 1
0 1
Expected Output
1
2
1
Loading Cloud IDE...
Ln 1, Col 1Spaces: 4UTF-8
pythonAuto-Saved

Input

3 3 4
0 0
0 1
1 2
2 1

Expected Output

1
1
2
3

Run or submit your code to see output here.