Representing an Image by a Binary Tree
Assignment
A raster picture P made of black and white pixels may be represented by its dimensions and a binary tree created according to the following rules:
-
If the pixels of P are all of the same color (white or black) then its tree representation consists of the root only and the root contains information about the pixels' color.
-
Let W (W ≥ 2) be the width of P, let X (1 ≤ X < W) be an integer. Let P1 be the rectangular part of P which consists of the first X columns of P. Analogously, let P2 be the rectangular part of P which consists of the last W−X columns of P. In this case, P may be represented by a tree which root contains the value of X and also an attribute specifying vertical division. Furthermore, the left subtree of the root is a tree representation of P1 and the right subtree of the root is a tree representation of P2.
-
Let H (H ≥ 2) be the height of P, let Y (1 ≤ Y < H) be an integer. Let P1 be the rectangular part of P which consists of the first Y rows of P. Analogously, let P2 be the rectangular part of P which consists of the last H−Y rows of P. In this case, P may be represented by a tree which root contains the value of Y and also an attribute specifying horizontal division. Furthermore, the left subtree of the root is a tree representation of P1 and the right subtree of the root is a tree representation of P2.
The tree representation of a picture may be constructed in various ways and the task is to optimize the tree. The optimization criterion is either the number of nodes or the tree depth. The examples of optimal trees are depicted in Image 1.
The task
A raster picture consisting of black and white pixels is given. Find its optimal tree representation in sense of minimal number of nodes and in sense of minimal depth. Note that these criteria are independent, the tree with minimum depth does not necessarily contain the minimum number of nodes and vice versa. Evaluate each criterion separately.
Input
The first line contains two positive integers M and N separated by space and representing (in this order) the number of rows (height) and the number of colums (width) of the input raster picture. Next, there are M input lines. The lines represent, from top to bottom, particular rows of pixes in the picture. Each row contains N symbols 0/1 separated by spaces. The symbols represent, from left to right, the pixels in the picture, 0 represents white color, 1 represents black color.
The values of M and N do not exceed 50.
Examples
Public data
The public data set is intended for easier debugging and approximate program correctness checking. The public data set is stored also in the upload system and each time a student submits a solution it is run on the public dataset and the program output to stdout and stderr is available to him/her.