297:Quadtrees

Quadtrees


建树递归,合并也递归。

在合并的时候要注意只有两个没有子节点的节点之间才可以合并,可能会遇到三种情况:

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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章