zoj 1788 Quad Trees

来源:互联网 发布:人工智能 哈工大 网盘 编辑:程序博客网 时间:2024/05/17 20:11

zoj 1788

先输入初始化MAP ,然后要根据MAP 建立一个四分树,自下而上建立,先建立完整的一棵树,然后根据四个相邻的格 值相同则进行合并,(这又是递归的伟大),逐次向上递归

四分树建立完后,再进行一深度优先遍历,生成二进制字符串,再转化为16进制输出


//#include "stdafx.h"#include <string.h>#include <string>#include <queue>#include <iostream>#include "stdio.h"using namespace std;char MAP[512][512];class quadtree//结点{public:char value[3];// "00"->all 0 ,"01"->all 1,"1"->mixedquadtree*q[4];//four childrenquadtree(){q[0] = q[1] = q[2] = q[3] = 0;//initialize four children }bool operator == (const quadtree &p)const//运算符重载,{if (strcmp(value, "1") == 0 || strcmp(value, p.value) != 0)return 0;elsereturn 1;}};quadtree * DFS(int r, int c, int s)//r ,c 坐标,s长度{int i; bool f = 1;quadtree*temp = new quadtree;if (s==1)//最小长度,每一个格{temp->value[0] = '0';temp->value[1] =  MAP[r][c];temp->value[2] = 0;//串结束符号?return temp;}s /= 2;//四分temp->q[0] = DFS(r, c, s);temp->q[1] = DFS(r, c + s, s);temp->q[2] = DFS(r + s, c, s);temp->q[3] = DFS(r + s, c + s, s);for (i = 1; i < 4;i++){if(!(*temp->q[0] == *temp->q[i]))//some of four children are different ,can not be merged{f = 0;break;}}if (f)//all children are same,merge{strcpy(temp->value, temp->q[0]->value);for (i = 0; i < 4; i++){delete temp->q[i]; temp->q[i] = 0;//delete all children }}else// don't merge{strcpy(temp->value, "1");}return temp;}string BFS(quadtree*root)//广度遍历,生成二进制字符串{string s = "";quadtree *cur = root;queue <quadtree*> que;que.push(root);while (!que.empty()){cur = que.front();que.pop();s += cur->value;for (int i = 0; i < 4; i++){if (cur->q[i]->value != NULL)//有子才放进去!!!!!!!que.push(cur->q[i]);}}return s;}////////////////////////////////////////////////转化为16进制。。别人家的代码char tohex(const string& str){int ret = 0;for (int i = 0; i < 4; i++) {ret <<= 1;//左移 实现16进制的转化if (str[i] == '1')++ret;}return (ret < 10) ? '0' + ret : 'A' + ret - 10;}string ToHex(const string& str){string tmp = str;string ret = "";while (tmp.length() % 4 != 0)tmp = "0" + tmp;for (size_t i = 0; i < tmp.length(); i += 4)ret += tohex(tmp.substr(i, 4));//substr 截取指定字符串,i为起始位置,4表示长度return ret;}////这部分是别人家的 = =///////////////////////////////////////////////////int  main(){string al;int k, N;scanf("%d", &k);//输入test 次数while (k--){scanf("%d", &N);for (int i = 0; i < N; i++)//输入矩阵大小{for (int  j = 0; j < N; j++){cin >> MAP[i][j];// scanf("%c", &MAP[i][j]);//initialize the array}}quadtree *root;root =DFS(0, 0, N);//build a quardtree;al = BFS(root);//cout << al << endl;cout << ToHex(al) << endl;}return 0;}




0 0
原创粉丝点击