BNUOJ 4049 四叉树

四叉树

Time Limit: 1000ms
Memory Limit: 65536KB
64-bit integer IO format: %lld      Java class name: Main
 

四叉树是一种常用的数据结构,广泛应用于栅格数据(如地图数据、遥感图像)的压缩编码中。将四叉树扩展到三维就形成了八叉树,可实现三维信息的压缩存储。下面是它的实现原理: 

 


如图是一个8*8图象,如果该图像所有元素都一样(都是0或都是1),就编码为0,再加上公共一样的元素(如01或00)。如果不一样,就先编码为1,然后把图像分成4个4*4图像。继续上面的操作,直到该小区域中,所有像素都是一样的元素为止(当然,最后可能只剩下一个象素点)。最后,(如(d)图)按照剖分的层次,自顶向下,从左至右,把所有的01序列连接起来。如上图,图像的编码为:100101100011000000010100010001 注意:同一层次四个小图象,合并的顺序是:左上、右上、左下,右下,如(d)图所示。 
本题要求同学们编程实现这一编码过程,输出压缩之后的0-1序列。 
 

 

Input

输入第一行,一个正整数n,一定是2的幂(2、4、8、16等等),最大不超过16 
下面是一个n*n的01矩阵,矩阵的元素只有0和1

 

Output

输出压缩之后的01序列,一个字符串,只有0和1

 

Sample Input

8
0 0 0 0 0 0 1 1
0 0 0 0 0 0 1 1
0 0 0 0 0 1 0 0
0 0 0 0 0 1 0 0
1 1 1 1 0 0 0 0
1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

Sample Output

100101100011000000010100010001

Source

 
解题:直接暴力
 
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 16;
 4 int n,mp[maxn][maxn];
 5 bool check(int x,int y,int w) {
 6     for(int i = 0; i < w; ++i) {
 7         for(int j = 0; j < w; ++j)
 8             if(mp[x][y] != mp[i+x][j+y])
 9                 return false;
10     }
11     return true;
12 }
13 string str[18];
14 void dfs(int x,int y,int w,int dep) {
15     string tmp = "1";
16     if(check(x,y,w)) {
17         tmp = "0";
18         if(mp[x][y] == 0) tmp += "0";
19         else tmp += "1";
20         str[dep] += tmp;
21         return;
22     }
23     str[dep] += tmp;
24     dfs(x,y,w>>1,dep+1);
25     dfs(x,y+(w>>1),w>>1,dep+1);
26     dfs(x+(w>>1),y,w>>1,dep+1);
27     dfs(x+(w>>1),y+(w>>1),w>>1,dep+1);
28 
29 }
30 int main() {
31     while(~scanf("%d",&n)) {
32         for(int i = 0; i < n; ++i)
33             for(int j = 0; j < n; ++j) {
34                 scanf("%d",mp[i] + j);
35             }
36         for(int i = 0; i < 18; ++i) str[i] = "";
37         dfs(0,0,n,0);
38         for(int i = 1; i <= log2(n); ++i)
39             str[0] += str[i];
40         cout<<str[0]<<endl;
41     }
42     return 0;
43 }
View Code
原文地址:https://www.cnblogs.com/crackpotisback/p/4639666.html