Water Filling
Time limit1sMemory limit512 MB
Given a grid where each column has at most one blocked segment, count the open cells where water pools after enough water is poured from the top.
- Level
Medium7 of 10
- Topics
- Implementation, Union-find
- Solved
- No attempts yet
Problem
There is an grid of cells. Call the top-left cell and the bottom-right cell . Directly below the bottom row is a floor that water cannot pass through.
Each cell is either blocked or open. Water cannot pass through a blocked cell. In each column, the blocked cells are either absent or form one contiguous block. Water also cannot pass between two adjacent blocked cells. A block in a column that includes a cell in the bottom row is called a block resting on the floor. A block that does not touch the floor is called a floating block.
When two blocks in adjacent columns contain a cell in the same row, the two blocks join into one block. Water cannot pass through the vertical boundary where they join. This joining applies to every pair of consecutive columns. The case in the figure where a block resting on the floor joins with a floating block, as in the second and third columns, is not given. In other words, blocks in adjacent columns join only when both rest on the floor or both float. The case where two blocks meet at only one corner, as in the fifth and sixth columns of the figure, is also not given.

For example, the figure below shows an grid. The first column is blocked from the 6th cell to the 8th cell, the second column has no blocked cells, and the third column is blocked from the 5th cell to the 8th cell.

Suppose enough water is poured in from the top. Water clearly pools in the cells marked 1, and in the cells marked 2. Water also pools in the cells marked 3 and 4. This part needs care. The problem assumes there is no air, so the cells marked 4 fill up to the same height as the cells marked 3. (The result is the same if you assume air passes through everything.) The cells marked 5 are where water pools on top of a floating block. Water does not pool in the situation shown by the cells marked 6.
Given the layout of the cells, write a program that prints the number of cells where water pools after enough water is poured in.
Input
The first line contains two integers and . () The next lines each contain two integers and . () From left to right, these give the rows through where the blocked cells are in the corresponding column. If a column has no blocked cells, both and are given as 0.
Output
Print the number of cells where water pools after enough water is poured onto the given grid.