建樹遞歸,合併也遞歸。
在合併的時候要注意只有兩個沒有子節點的節點之間纔可以合併,可能會遇到三種情況:
1. 兩個都是最小單元(相對本身),直接合並;
2. 其中一個有子節點,依次其將其子節點與另一個節點合併;
3. 兩個都有子節點,依次將其子節點按順序進行合併(兩者此時子節點面積必定相同,思考一下即可)。
其中unit 爲最小單元面積,每次劃分都變爲其本身的1/4,上述過程遞歸進行即可。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10000 + 5;
int cnt;
struct node{
char id = 0;
struct node* son[4] = {NULL};
};
node* newnode(){ return new node; }
node* build(){
node* root = newnode();
char c = getchar();
if(c != 'p'){ root->id = c; return root; }
for(int i = 0;i < 4;i++) root->son[i] = build();
return root;
}
void Union(node* a,node* b,int unit){
if(a->id && b->id){
if(a->id == 'f' || b->id == 'f') cnt += unit;
}
else if(a->id && !b->id){
for(int i = 0;i < 4;i++) Union(a,b->son[i],unit/4);
}
else if(!a->id && b->id){
for(int i = 0;i < 4;i++) Union(a->son[i],b,unit/4);
}
else{
for(int i = 0;i < 4;i++) Union(a->son[i],b->son[i],unit/4);
}
}
int main(){
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
int t = 0;
scanf("%d\n",&t); //pay attention to '\n'!!!
while(t--){
node* a = build(); getchar();
node* b = build(); getchar();
cnt = 0;
int unit = 1024;
Union(a,b,unit);
printf("There are %d black pixels.\n",cnt);
}
return 0;
}