1.题目描述:点击打开链接
2.解题思路:本题考查四分树的遍历。本题实质上是已知一棵四分树求黑色结点的编号;已知黑色结点的编号反过来构造四分树。第一种情况相当于编码,我们用先序遍历解决。用encode函数表示给整个四分树编码,如果发现内部既有0又有1出现,那么将其均分为四份,递归编码;反之则统计该结点的颜色以及路径。这里把路径编码成一个十进制数,便于转换。同理,如果已知了黑色结点,那么首先解码出来每个点的路径,然后从坐标原点沿着它的路径找到它的起始点,随后把这片区域标记为‘*’即可。
注意:本题要看清输出格式,对于第一种情况,满12个要换行。
3.代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<string> #include<sstream> #include<set> #include<vector> #include<stack> #include<map> #include<queue> #include<deque> #include<cstdlib> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<functional> using namespace std; const int N = 64 + 5; char g[N][N]; vector<int>code; int n; struct Node { int color; int dir; }node[N*N]; void encode(int r, int c, int w, int dir, int &id)//分别表示:起点坐标r,起点坐标c,宽w,编码后的方向,结点编号 { int ok = 1; char ch = g[r][c]; for (int i = r; i < r + w; i++) for (int j = c; j < c + w; j++) if (g[i][j] != ch) { ok = 0; break; } if (ok)//找到了一个结点 { node[id].color = (ch == '0' ? 0 : 1); int x = dir, k = 1; stack<int>s; while (x>0) { s.push(x % 10); x /= 10; } while (!s.empty())//利用一个栈把5进制数翻转后转换成10进制 { node[id].dir += s.top()*k; s.pop(); k *= 5; } id++; } else//递归编码 { encode(r, c, w / 2, dir * 10 + 1, id); encode(r, c + w / 2, w / 2, dir * 10 + 2, id); encode(r + w / 2, c, w / 2, dir * 10 + 3, id); encode(r + w / 2, c + w / 2, w / 2, dir * 10 + 4, id); } } void draw(int r, int c, int w) { for (int i = r; i < r + w; i++) for (int j = c; j < c + w; j++) g[i][j] = '*'; } void decode(vector<int> s) { int len = s.size(); for (int i = 0; i < len; i++) { int x = s[i], k = 1; node[i].color = 1; while (x>0)//解码出路径,低位是低层的路径 { node[i].dir += (x % 5)*k; x /= 5, k *= 10; } } for (int i = 0; i < len; i++) { int dir = node[i].dir; int r = 0, c = 0, w = n; while (dir>0)//沿着路径找到对应的区域 { int x = dir % 10; if (x == 1)w /= 2; if (x == 2){ c += w / 2; w /= 2; } if (x == 3){ r += w / 2; w /= 2; } if (x == 4){ r += w / 2; c += w / 2; w /= 2; } dir /= 10; } draw(r, c, w); } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (g[i][j] != '*') g[i][j] = '.'; for (int i = 0; i < n; i++) puts(g[i]); } int main() { //freopen("t.txt","r", stdin); int rnd = 0; while (~scanf("%d", &n) && n) { memset(g, '\0', sizeof(g)), code.clear(); memset(node, 0, sizeof(node)); if (rnd)puts(""); printf("Image %d\n", ++rnd); if (n > 0) { for (int i = 0; i < n; i++) scanf("%s", g[i]); int id = 1; encode(0, 0, n, 0, id);//对整个图片进行编码 vector<int>tmp; for (int i = 1; i < id; i++) if (node[i].color == 1) tmp.push_back(node[i].dir); sort(tmp.begin(), tmp.end()); for (int i = 0; i < tmp.size(); i++) { printf("%d", tmp[i]); if ((i + 1) % 12 == 0 || i == tmp.size() - 1)printf("\n"); else printf(" "); } printf("Total number of black nodes = %d\n", tmp.size()); } else { n = -n; int x; while (~scanf("%d", &x) && x != -1) code.push_back(x); decode(code);//解码后画图 } } return 0; }
原文地址:http://blog.csdn.net/u014800748/article/details/44866133