297 - Quadtrees*****

本文介绍了一种使用四叉树的数据结构解决特定问题的方法。通过创建两棵四叉树,并实现它们的合并,最后遍历合并后的树来计算黑色像素的数量。文章提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 解题要有恒心。。。。 不错的一道题,当时没有解出。***** 这道题主要步骤: *创建一颗四叉树 *合并 *历编 不可盲目去寻找错误,选一测试案例,自己认真走一遍试试 */ #include <iostream> #include <cstdio> #include <string> #include <cstdlib> using namespace std; struct Node { char ch; Node *fir,*sec,*thi,*fou; }; string a; int sum; Node *creat(int &loc) { /* 创建树的步骤: 步骤1:分配内存 步骤2:递归调用 */ Node *r=(Node *)malloc(sizeof(Node)); if(loc<a.size()) { r->ch=a[loc]; if(a[loc]=='p') { r->fir=creat(++loc); r->sec=creat(++loc); r->thi=creat(++loc); r->fou=creat(++loc); } else r->fir=r->sec=r->thi=r->fou=NULL; } return r; } Node *combine(Node *root1,Node *root2) { Node *r=(Node *)malloc(sizeof(Node)); if(root1->ch=='f' || root2->ch=='f') { r->ch='f'; r->fir=r->sec=r->thi=r->fou=NULL; } else if(root1->ch=='e' && root2->ch=='e') { r->ch='e'; r->fir=r->sec=r->thi=r->fou=NULL; } else { r->ch='p'; if(root1->ch=='p' && root2->ch=='p') { r->fir=combine(root1->fir,root2->fir); r->sec=combine(root1->sec,root2->sec); r->thi=combine(root1->thi,root2->thi); r->fou=combine(root1->fou,root2->fou); } else if(root1->ch=='p' && root2->ch=='e') { r->fir=root1->fir; r->sec=root1->sec; r->thi=root1->thi; r->fou=root1->fou; } else { r->fir=root2->fir; r->sec=root2->sec; r->thi=root2->thi; r->fou=root2->fou; } } return r; } void cacluate(Node *root,int len) { /* if(root->ch=='p') { len=len/4; cacluate(root->fir,len); cacluate(root->sec,len); cacluate(root->thi,len); cacluate(root->fou,len); } else if(root->ch=='f') sum+=len; */ if(root!=NULL) { if(root->ch=='f') sum+=len; len=len/4; cacluate(root->fir,len); cacluate(root->sec,len); cacluate(root->thi,len); cacluate(root->fou,len); } } int main() { //freopen("data.in","r",stdin); //freopen("data.out","w",stdout); int T; cin>>T; while(T--) { int loc; loc=0; cin>>a; Node *root1=creat(loc); cin>>a; loc=0; Node *root2=creat(loc); Node *root=combine(root1,root2); sum=0; cacluate(root,1024); printf("There are %d black pixels.\n",sum); } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值