Number of Paint Colors
Time limit2sMemory limit128 MB
Count connected regions of a rectangle cut by up to 1000 axis-aligned masking tape rectangles, where regions sharing only a corner stay separate.
- Level
Medium7 of 10
- Topics
- Combinatorics, Geometry, Union-find
- Solved
- No attempts yet
Problem
To advertise an informatics olympiad, you want to make a signboard by painting a rectangular plywood board. On the parts of the board that should stay unpainted, several rectangular strips of masking tape have already been applied. You therefore decide to paint each region separated by the masking tape with a different color. For example, the board in Figure 5-1 uses 5 colors of paint.

Figure 5-1 An example signboard
Two regions that share a boundary segment of positive length are considered to be connected into one region and are painted the same color, while two regions that touch only at a single corner point are counted as different regions.
Given the positions where the masking tape is applied, write a program that computes the number of paint colors used. It is guaranteed that the whole board is never completely covered by masking tape, and every side of every masking tape is parallel to one of the sides of the board.
Input
The first line contains the width (an integer with ) and the height (an integer with ) of the plywood board, in this order, separated by a space.
The second line contains the number of masking tapes (an integer with ). Each of the following lines, the -th line (), contains the bottom-left coordinate and the top-right coordinate of the -th masking tape, given as (integers with and ), separated by spaces.
The bottom-left corner of the board is at and the top-right corner is at .
Output
Print the number of paint colors used on a single line.
Hint
The following figure shows the input example corresponding to the signboard in Figure 5-1.

Figure 5-2 Input example for the signboard in Figure 5-1