Painting a Board
Time limit1sMemory limit128 MB
Given up to 15 rectangles with colors and vertical precedence constraints, find the minimum number of brush pick-ups to paint every rectangle.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Bit manipulation, Graph, Topological sort
- Solved
- No attempts yet
Problem
The CE Digital company has built an Automatic Painting Machine (APM) that paints a flat board. The board is completely covered by adjacent, non-overlapping rectangles of various sizes, and each rectangle has a single predefined color.

The APM has a set of brushes, one distinct color per brush. To paint the board, the machine repeatedly picks up a single brush of some color and, while holding it, paints one or more rectangles whose predefined color is . Painting obeys the following rules:
- To keep the paints from leaking and colors from mixing, a rectangle may be painted only after every rectangle immediately above it has already been painted. (In Figure 1, rectangle can be painted only after rectangles and have been painted.)
- Each rectangle must be painted in a single pass; partial painting of a rectangle is not allowed.
Write a program that paints the whole board while minimizing the number of brush pick-ups. If the same brush is picked up more than once, every pick-up is counted.
Input
The first line contains an integer , the number of test cases ().
Each test case begins with a line containing an integer , the number of rectangles (). The next lines each describe one rectangle with five integers:
where is the upper-left corner and is the lower-right corner of the rectangle, and is its color code.
- The color code is an integer with .
- The upper-left corner of the board is always .
- Every coordinate is in the range .
Output
For each test case, print a single line containing the minimum number of brush pick-ups.