297 - Quadtrees
来源:互联网 发布:中国银行上海软件中心 编辑:程序博客网 时间:2024/05/01 06:16
描述:这道题就是求像素相加问题,给出了两个四叉树的先序输出,构建完这两个四叉树再合并,然后计算像素结果就ok了,注意,像素开始值是1024,也就是说输出如果大于1024就程序错了,关键是能够合并两个四叉树#include <iostream>#include <cstdio>#include <cstring>using namespace std;struct Tnode{ char v; struct Tnode *first,*second,*third,*fourth; Tnode () { v=0; first=second=third=fourth=NULL; }};int len;Tnode *creat_two_tree(char *b)//创建四叉树{ Tnode *tree=new Tnode; if(len<strlen(b)) { tree->v=b[len]; if(b[len]=='p') { len++;//注意len++有四个,不是一个 tree->first=creat_two_tree(b); len++; tree->second=creat_two_tree(b); len++; tree->third=creat_two_tree(b); len++; tree->fourth=creat_two_tree(b); } } return tree;}Tnode *creat_new_tree(Tnode *b, Tnode *c)//合并四叉树{ Tnode *tree=new Tnode; if(b->v=='f'||c->v=='f')tree->v='f'; else if(b->v=='e'&&c->v=='e')tree->v='e'; else { tree->v='p'; if(b->v=='p'&&c->v=='p') { tree->first=creat_new_tree(b->first,c->first); tree->second=creat_new_tree(b->second,c->second); tree->third=creat_new_tree(b->third,c->third); tree->fourth=creat_new_tree(b->fourth,c->fourth); } else if(b->v=='p'&&c->v=='e') { tree->first=b->first; tree->second=b->second; tree->third=b->third; tree->fourth=b->fourth; } else { tree->first=c->first; tree->second=c->second; tree->third=c->third; tree->fourth=c->fourth; } } return tree;}void sum(Tnode *tree,int count)//计算像素值和{ if(tree) { if(tree->v=='f')len+=count; count/=4; sum(tree->first,count); sum(tree->second,count); sum(tree->third,count); sum(tree->fourth,count); }}int main(){ //freopen("a.txt","r",stdin); int n; char s1[10010],s2[10010]; scanf("%d",&n); while(n--) { memset(s1,0,sizeof(s1)); memset(s2,0,sizeof(s2)); scanf("%s%s",s1,s2); len=0; Tnode *root1=creat_two_tree(s1); len=0; Tnode *root2=creat_two_tree(s2); Tnode *root=creat_new_tree(root1,root2); len=0; sum(root,1024); printf("There are %d black pixels.\n",len); } return 0;}