UVa 297 - Quadtrees

本文介绍了一种使用深度优先搜索(DFS)算法遍历图像并统计黑色像素数量的方法。通过构建1024大小的数组表示图像,并将黑色节点对应区域标记为1,最后统计数组中1的数量来得到黑色像素总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
dfs+暴力,建立一个1024数组代表图像,接着dfs遍历,把每个黑色节点对应的地图区域设置为1.
最好统计数组中1的个数
*/
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <queue>
using namespace std;
char a[3000];
char vis[1024];
int st;

//dfs返回值表示该子树在字符串中占用字符数
int dfs(int i, int c)
{
    if(a[i] == 'f') {
        memset(vis+st, 1, sizeof(vis[0])*c);
        st += c;
        return 1;
    } else if(a[i] == 'p') {
        int cnt = 1;
        for(int j=0; j<4; j++) {
            cnt += dfs(i+cnt, c/4);
        }
        return cnt;
    } else {
        st += c;
        return 1;
    }
}

int cnt()
{
    int s = 0;
    for(int i=0; i<1024; i++) {
        if(vis[i]) s++;
    }
    return s;
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    int T;
    scanf("%d", &T);
    while(T--) {
        memset(vis, 0, sizeof(vis));
        st = 0;
        scanf("%s", a);
        dfs(0, 1024);
        st = 0;
        scanf("%s", a);
        dfs(0, 1024);
        printf("There are %d black pixels.\n", cnt());
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值