传送门UVa 699 - The Falling Leaves
树的题目.
思路很简单, 建树, 然后求在同一列上的和.
一开始在统计树叶那里没思路, 不知道怎么判断是不是在同一列上. 后来看到其他人的思路, 从根开始, 往左就-1, 往右+1, 如果数字一样就在一列上... 其实我一开始就是想通过这种方法的, 但是怎么也想不起来.
因为题目说最大的宽度是80, 所以开一个80的数组存就行. 根节点的下标就是39.
后来在读取数据的时候也出了问题, 怎么判断一棵树读完了呢?
想了一会儿, 我去, 递归兄在这里, 我不是瞎操心么...(╯‵□′)╯ ┴─┴
还是得多做题啊....
挺好理解的, 就不注释了.
详情见代码
#include <cstdio>
#include <cstring>
using namespace std;
struct Node
{
Node *left, *right;
Node()
{
left = right = NULL;
}
};
Node *Input(int pos);
void Output();
const int MAXN = 80;
int sum[MAXN] = {0};
int main()
{
//freopen("input.txt", "r", stdin);
int i, cnt = 1;
while (true)
{
Node *root = Input(39);
if (root == NULL)
break;
printf("Case %d:\n", cnt++);
Output();
memset(sum, 0, sizeof(sum));
}
return 0;
}
Node *Input(int pos)
{
Node *root;
int temp;
scanf("%d", &temp);
if (temp == -1)
return NULL;
else
{
root = new Node();
sum[pos] += temp;
root->left = Input(pos - 1);
root->right = Input(pos + 1);
}
return root;
}
void Output()
{
int i;
bool flag = true;
for (i = 0; i < MAXN; i++)
if (sum[i] != 0)
{
if (flag == true)
{
flag = false;
printf("%d", sum[i]);
}
else
printf(" %d", sum[i]);
}
printf("\n\n");
}