UVA 297 Quadtrees

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));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值