uva 297 - Quadtrees

来源:互联网 发布:作谱软件 编辑:程序博客网 时间:2024/04/27 23:52

四叉树,p代表后面4个字符代表下面四个子结点的状态,f则为黑,e则为白。

题目中说深度不超过5层,不知道算了根结点没,我觉得按照32*32应该是6层。

我的方法是不管如果是f和e则将它下面的结点(假象存在)全部标记,最后两个相加的时候只用判断是否有任意一个这个点为黑即可。

若为p则判断下一个字符。

#include<cstdio>#include<cstring>const int MAXN=3000;char a[MAXN];bool b[2][MAXN];int i,n;void tree(int depth,char c,int cnt){    if(depth==6){        if(c=='f') b[cnt][n]=true;        else b[cnt][n]=false;        n++;        return ;    }    else{        if(c=='f'){            for(int j=0;j<4;j++)            tree(depth+1,c,cnt);        }        else if(c=='e'){            for(int j=0;j<4;j++)            tree(depth+1,c,cnt);        }        else if(c=='p'){            for(int j=0;j<4;j++)            {i++;tree(depth+1,a[i],cnt);}        }    }}int main(){    //freopen("in.txt","r",stdin);    //freopen("out.txt","w",stdout);    int T;    scanf("%d",&T);    getchar();    while(T--){        memset(b,false,sizeof(b));        gets(a);n=0;i=0;        tree(1,a[0],0);        gets(a);n=0;i=0;        tree(1,a[0],1);        int ans=0;        for(int j=0;j<n;j++){            if(b[0][j] || b[1][j]) ans+=1;        }        printf("There are %d black pixels.\n",ans);    }    return 0;}

 

遇到f和e直接算出来,不用递归的,不过这个为啥还慢些。。。

#include<cstdio>#include<cstring>#include<cmath>const int MAXN=3000+10;char a[MAXN];bool b[2][MAXN];int i,n;void tree(int depth,char c,int cnt){    if(c=='f'){        int temp=pow(4,6-depth);        for(int j=0;j<temp;j++){            b[cnt][n]=true;            n++;        }        return ;    }    else if(c=='e'){        int temp=pow(4,6-depth);        for(int j=0;j<temp;j++){            b[cnt][n]=false;            n++;        }        return ;    }    else if(c=='p'){        for(int j=0;j<4;j++)        {i++;tree(depth+1,a[i],cnt);}    }}int main(){    //freopen("in.txt","r",stdin);    //freopen("out.txt","w",stdout);    int T;    scanf("%d",&T);    getchar();    while(T--){        memset(b,false,sizeof(b));        gets(a);n=0;i=0;        tree(1,a[0],0);        gets(a);n=0;i=0;        tree(1,a[0],1);        int ans=0;        for(int j=0;j<n;j++){            if(b[0][j] || b[1][j]) ans+=1;        }        printf("There are %d black pixels.\n",ans);    }    return 0;}


 

 

0 0
原创粉丝点击