题目中定义的四叉树,顶点若为黑色则一共有1024个像素,从这里可以推断出四叉数的曾数是6,最后一层的值为1, 思路是递归建树,然后遍历/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define PARENT 1
#define FULL 2
#define EMPTY 3
#define CHILDCNT 4
#define MAXN 2048
#define MAXV 1365
typedef struct BTREENODE_ {
int data_type;
BTREENODE_ *child[CHILDCNT];
}BTREENODE;
int rst[MAXN], pos;
void build_tree(const char *str, BTREENODE **node)
{
(*node) = new BTREENODE;
if( 'p' == str[++ pos] ) {
(*node)->data_type = PARENT;
for(int i = 0; i < CHILDCNT; i ++) {
build_tree(str, &(*node)->child[i]);
}
return;
}
(*node)->data_type = ('f' == str[pos])? FULL : EMPTY;
for(int i = 0; i < CHILDCNT; i ++) {
(*node)->child[i] = NULL;
}
}
inline int get_child_index(const int &cur_idx, int ith_child)
{
return (cur_idx-1)*CHILDCNT+ith_child+2;
}
void loop_set_rst(const int &idx)
{
if( idx > MAXV ) {
return;
}
rst[idx] = (get_child_index(idx, 0) > MAXV)? 1 : 0;
for(int i = 0; i < CHILDCNT; i ++) {
loop_set_rst(get_child_index(idx, i));
}
}
void set_rst(BTREENODE *node, int cur_idx)
{
if( cur_idx > MAXV ) {
return;
}
if( PARENT == node->data_type ) {
for(int i = 0; i < CHILDCNT; i ++) {
set_rst(node->child[i], get_child_index(cur_idx, i));
}
}
else if( FULL == node->data_type ) {
rst[cur_idx] = (get_child_index(cur_idx, 0) > MAXV)? 1 : 0;
for(int i = 0; i < CHILDCNT; i ++) {
loop_set_rst(get_child_index(cur_idx, i));
}
}
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int n, ans;
char str[MAXN];
BTREENODE *root;
while( ~scanf("%d", &n) ) {
for(int i = 0; i < n; i ++) {
memset(rst, 0, sizeof(rst)); ans = 0;
for(int k = 0; k < 2; k ++) {
scanf("%s", str); pos = -1;
build_tree(str, &root); set_rst(root, 1);
}
for(int i = 1; i < MAXN; i ++) {
ans += rst[i];
}
printf("There are %d black pixels.\n", ans);
}
}
return 0;
}
uva_297_Quadtrees
最新推荐文章于 2021-03-03 18:01:01 发布