dfs uva-297-Quadtrees

來源:互聯網
上載者:User

 

題目連結:

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=233

 

題目意思:

給兩顆四叉樹,每層有一個值,只要有一個為黑則為黑,否則為白,求兩樹的和。

 

解題思路:

用遞迴建樹,用dfs求和。

 

代碼:

#include<iostream>#include<cmath>#include<cstdio>#include<cstdlib>#include<string>#include<cstring>#include<algorithm>#include<vector>#include<map>#include<stack>#include<queue>#define eps 1e-6#define INF (1<<20)#define PI acos(-1.0)typedef  struct Node node;using namespace std;struct Node{    int black;    node * son[4];  //四個孩子的節點指標};char string1[2000],string2[2000];char *p;int sum;node * build(){    node * temproot=(node *)malloc(sizeof(node));    if(*p=='p')    {        temproot->black=0;        for(int i=0;i<4;i++)  //一定有四個孩子        {            p++;            temproot->son[i]=build();        }    }    else    {        if(*p=='f')            temproot->black=1;        else            temproot->black=0;        for(int i=0;i<4;i++)   //分別為葉子節點            temproot->son[i]=NULL;       // p++;  //注意p不用加    }    return temproot;}void dfs(node * root1,node *root2,int height){    if(root1==NULL&&root2==NULL)  //兩棵樹都加完了        return ;    if(root1==NULL)  //如果第一棵樹此節點為葉子節點,則按第二棵樹的情況來處理    {       if(root2->black)       {           sum+=(1024>>(height*2));  //每個一層除以4           return ;       }       else       {           for(int i=0;i<4;i++)  //將此以此節點為根的子樹全部算完             dfs(root1,root2->son[i],height+1);           return ;       }    }    if(root2==NULL) //如果第二棵樹此節點為葉子節點,則按第一棵樹的情況來處理    {        if(root1->black)        {            sum+=(1024>>(2*height));            return ;        }        else        {            for(int i=0;i<4;i++)                dfs(root1->son[i],root2,height+1);            return;        }    }    if(root1->black||root2->black)  //如果有一個為黑,則後面的統統不用算    {        sum+=(1024>>(height*2));        return ;    }    for(int i=0;i<4;i++)  //兩個都是白色的,繼續        dfs(root1->son[i],root2->son[i],height+1);    return ;}int main(){    int ca;    scanf("%d",&ca);    while(ca--)    {        scanf("%s%s",string1,string2);        p=string1;   //用兩個指標來訪問,統一,簡便        node * tree1=build();        p=string2;        node * tree2=build();        sum=0;        int height=0;        dfs(tree1,tree2,height);  //用兩個根來訪問兩棵樹        printf("There are %d black ",sum);        sum==1?printf("pixel.\n"):printf("pixels.\n");    }    return 0;}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.