題目連結:
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;}