UVa 297 - Quadtrees解题报告

来源:互联网 发布:ecshop 打印sql语句 编辑:程序博客网 时间:2024/06/05 16:21

题意:给定两个字符串,字符p对应建立子树,字符e为白色,f为黑色对于不同层黑点f对应不同的值,最上面为1024下来为每个子树256.....,这样建立两颗四叉树,计算两颗树相加后的黑点f对应的值,注意在两颗树上同一点处,只要有一个为黑点,那么相加后就为黑点

思路:首先建立两颗树,采用递归建树的方法 ,建完树后利用前序遍历的方法进行递归求解和

#include <iostream>#include <cstring>#include <cmath>using namespace std;const int maxn = 1100;struct Nobe{char ch;Nobe *children[4];Nobe();};Nobe::Nobe(){ch = 0;for(int i = 0; i < 4; i++)children[i] = NULL;}char str1[maxn], str2[maxn];int sum, pos;Nobe * CreatTree(Nobe *, char *);void DFS(Nobe *, Nobe *, int);int main(){freopen("data.txt", "r", stdin);int cases;scanf("%d", &cases);while (cases--){scanf("%s", str1);scanf("%s", str2);pos = -1;Nobe *root1 = new Nobe;root1 = CreatTree(root1, str1);pos = -1;Nobe *root2 = new Nobe;root2 =CreatTree(root2, str2);sum = 0;DFS(root1, root2, 0);printf("There are %d black pixels.\n" , sum); }}Nobe * CreatTree(Nobe *root, char *str)//这样建立的树,叶子节点的孩子为空{pos++;if(pos == strlen(str))return NULL;root = new Nobe;root->ch = str[pos];if(root->ch == 'p')//如果有孩子节点for(int i = 0; i < 4; i++)if(root->children[i] == NULL)//节点为空root->children[i] = CreatTree(root, str);return root;}//分三种情况遍历两棵树。1,两个根为空。2,一个为空,另一不为空。3,都不为空void DFS(Nobe *root1, Nobe *root2, int level)//同时遍历两棵树{if(root1 == NULL && root2 == NULL)return;if(root1 == NULL){if(root2->ch == 'f')//为f肯定没有孩子节点{sum += 1024 / pow(4, level);return;}for(int i = 0; i < 4; i++)//有孩子节点遍历孩子DFS(root1, root2->children[i], level + 1);return;}if(root2 == NULL)//{if(root1->ch == 'f'){sum += 1024 / pow(4, level);return;}for(int i = 0; i < 4; i++)DFS(root1->children[i], root2, level + 1);return;}if(root1->ch == 'f' || root2->ch == 'f'){sum += 1024 / pow(4, level);return;}for(int i = 0; i < 4; i++)DFS(root1->children[i], root2->children[i], level + 1);}


0 0
原创粉丝点击