Quad Tree
Time limit1sMemory limit128 MB
Parse an XBM hex bitmap, then recursively encode it as a quad tree: uniform squares become B or W, mixed ones become Q followed by four sub-squares.
- Level
Medium4 of 10
- Topics
- Divide and conquer, Recursion, Implementation, Bit manipulation
- Solved
- No attempts yet
Problem
Treasure hunter Hanshin discovered that the treasure map he brought back from the ruins of the Aztec civilization is a fake. Furious, he plans to prank people by sending this fake map not only to himself but to others as well. But if just anyone could read the map easily, Hanshin would be in trouble. So let's help Hanshin encrypt the map!
The map is given in XBM format, and you must compress and encode it into a quad tree structure.
Input
The input is a black-and-white image in XBM format, given as follows.
- Line 1:
#define quadtree_width n— here is the image width in pixels. The image is a square of pixels. - Line 2:
#define quadtree_height n— the image height in pixels, equal to the width . - Line 3:
static char quadtree_bits[] = { - The next lines: each line represents one row of the image; that row's pixel values are given as hexadecimal values.
- Each hexadecimal value has 8 bits and represents 8 pixels from left to right. The leftmost pixel has bit value , and the rightmost pixel has bit value .
- A black pixel (B) has its bit set (1); a white pixel (W) has its bit unset (0).
- Each hexadecimal value is given in the form
0xdd, where eachdis one of0–9,a–f. The values are separated by commas (,). - For example, the 8 pixels
WBBBBWWBare written as0x9e(2 + 4 + 8 + 16 + 128 = 158 = 0x9e).
- Last line:
};
is a power of two with .
Output
On the first line, print the image size .
On the second line, print the string that encodes the image as a quad tree. The encoding is defined recursively as follows.
- If every pixel in the current square region has the same color, print that color as a single character:
Bif all pixels are black,Wif all pixels are white. - Otherwise, print
Q, then split the region into four equal quadrants and recursively encode each one in the order top-left, top-right, bottom-left, bottom-right.
Starting from the whole image, apply this rule and print the resulting string on one line with no spaces.