您的位置:首页 > 其它

UVa 297 - Quadtrees

2014-04-19 16:12 357 查看
传送门UVa 297 - Quadtrees

树的题目.

题意是给你两颗树, 然后让他们合并, 求黑色像素的值.

参考了别人的解题报告.

解题方法是先按题目给的值重建两棵树, 然后按要求合并成一棵树, 最后用BFS计算出总的像素.

通过这题也学到了很多.

详情见代码

#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;

struct node
{
node *child[4];
char data;
};

node *Build(int &a, const char tree[]);
node *Combine(node *root1, node *root2);
void GetAnswer(node *root1, int n, int &ans);

int main()
{
//freopen("input.txt", "r", stdin);
int T;
scanf("%d", &T);
getchar();
while (T--)
{
node *root1, *root2;
char tree1[10000];
char tree2[10000];
scanf("%s", tree1);
getchar();
scanf("%s", tree2);
int a, b;
a = b = 0;
root1 = Build(a, tree1);
root2 = Build(b, tree2);
root1 = Combine(root1, root2);
int ans = 0;
GetAnswer(root1, 1, ans);
printf("There are %d black pixels.\n", ans);
}
return 0;
}

node *Build(int &a, const char tree[])
{
node *root = (node *)malloc(sizeof(node));
root->data = tree[a];
for (int i = 0; i < 4; i++)
root->child[i] = 0;
if(tree[a] == 'p')
for (int i = 0; i < 4; i++)
root->child[i] = Build(++a, tree);
return root;
}

node *Combine(node *tree1, node *tree2)
{
if (tree1 == NULL)
return tree2;
else if (tree2 == NULL)
return tree1;
else if (tree1->data == 'f' || tree2->data == 'f')
{
node *tree1 = (node *)malloc(sizeof(node));
tree1->data = 'f';
for (int i = 0; i < 4; i++)
tree1->child[i] = 0;
return tree1;
}
if (tree2->data == 'p')
tree1->data = 'p';
for (int i = 0; i < 4; i++)
tree1->child[i] = Combine(tree1->child[i], tree2->child[i]);
return tree1;
}

void GetAnswer(node *root, int level, int &ans)
{
if (root)
{
//printf("%c", root->data);
if (root->data == 'f')
{
if (level == 1)
ans += 1024;
else if (level == 2)
ans += 256;
else if (level == 3)
ans += 64;
else if (level == 4)
ans += 16;
else if (level == 5)
ans += 4;
else if (level == 6)
ans += 1;
}
for (int i = 0; i < 4; i++)
GetAnswer(root->child[i], level + 1, ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM UVa 297