UVA-297
题意:一个有1024个格子的像素块,给出 2 个完全四叉树的先序,求两个重叠后涂成黑色的格子数。其中e为白色,f为黑色,p为非叶子节点。
解题思路:首先要理解四叉树是如何染色的。如题目中所表示的,每个节点若存在子节点,处理方式为将当前的正方形四等分,然后用每科子树对应一个1 / 4的正方形去染色。
我们可以dfs遍历,当当前节点为p时读取它的四个子树,当前节点为e或f时染色并返回上一层(其实遇到f染色,遇到e不管他直接返回就是了)。
因为只有1024格,满四叉树最多有 1024 + 256 + 64 +16 +4 +1 < 1400的节点。然后推了一下对于满二叉树中第i个点,它的儿子节点范围为 i*4-2 to i*4+1。两次染色完从1开始深度遍历,如果当前节点为f,就增加对应正方形的面积,最多跑到 1024 + 256 + 64 +16 +4 +1就完了。
/*************************************************************************
> File Name: UVA-297.cpp
> Author: Narsh
>
> Created Time: 2016年07月18日 星期一 18时54分06秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
struct node{
char color;
}p[13330];
int t,n,l;
const int c[9]={1024,256,64,16,4,1,0,0,0};
string s;
void dfs(int t) {
l++;
if (s[l] == 'f'){
p[t].color = 'f';
return ;
}
if (s[l] == 'e') return ;
for (int i = 1; i <= 4; i++)
dfs(t*4-3+i);
}
int tot(int t, int x) {
if (t >= 1400) return 0;
if (p[t].color == 'f') return c[x];
int sum=0;
for (int i = 1; i <= 4; i++)
sum+=tot(t*4-3+i,x+1);
return sum;
}
int main() {
scanf("%d",&t);
while (t--) {
for (int i = 1; i <= 1422; i++)
p[i].color=' ';
cin>>s;
s=" "+s;
l=0;
dfs(1);
cin>>s;
s=" "+s;
l=0;
dfs(1);
printf("There are %d black pixels.\n",tot(1,0));
}
}