Quad Tree
InterviewTime limit1sMemory limit128 MB
Decode a quad tree string into an n by n black and white image, then print each row as XBM hexadecimal bytes.
- Level
Medium5 of 10
- Topics
- Recursion, Divide and conquer, Implementation, Bit manipulation
- Solved
- No attempts yet
Problem
While searching for treasure at an ancient Aztec ruin, Hanshin found a papyrus scroll covered with a long text. The text was made of only three kinds of characters: , , and .
Having studied a little cryptography, Hanshin recognized this as a famous 3000-year-old quad tree encoding.
Quad tree encoding compresses a picture (such as a treasure map) with the following rules:
- If the whole picture is black, encode it as .
- If the whole picture is white, encode it as .
- If it contains both black and white parts, encode it as : recursively split the picture into four parts in the order top-left, top-right, bottom-left, bottom-right, and encode each part () again.
Every picture is an square of pixels where is a power of two, and it is always encoded as a perfect quad tree.
For example, a checkerboard is written as , and a checkerboard is written as .
Write a program that decodes such a quad tree string into an XBM-format file.
Input
The first line contains an integer (), the width and height of the picture in pixels; is always a power of two.
The second line contains a string of only , , and that encodes the picture as a quad tree.
Output
Print the XBM file contents in the following format:
- Line 1:
#define quadtree_width n, where is the width in pixels. - Line 2:
#define quadtree_height n, where is the height in pixels. - Line 3:
static char quadtree_bits[] = { - The next lines: each row of the picture converted into hexadecimal values. Each hex value packs 8 pixels from left to right into an 8-bit number, where the leftmost pixel has bit value 1 and the rightmost pixel has bit value 128. A black pixel is 1 and a white pixel is 0. Write each value in the form
0xdd(two lowercase hex digits) and append a comma (,) after every value. For example, the 8 pixels give =0x9e. - Last line:
};