题目:(UVA-679)
原来的英文题目太长,下面是原题大意:
有一个满二叉树,给出二叉树的层数 D 和小球的个数 I ,初始每一个节点值都为false,不断有小球从根节点落下,每经过一个节点,判断该节点的值,若为false,则接下来往左走,否则往右走,然后将该节点的值取反,问最后一个小球落在哪一个叶子节点上。
Input
Contains l + 2 lines.
Line 1 l the number of test cases
Line 2 D1 I1 test case #1, two decimal numbers that are separated by one blank
...
Line k + 1 Dk Ik test case #k
Line l + 1 Dl Il test case #l
Line l + 2 -1 a constant ‘-1’ representing the end of the input file
Output
Contains l lines.
Line 1 the stop position P for the test case #1
...
Line k the stop position P for the test case #k
...
Line l the stop position P for the test case #l
Sample Input
5
4 2
3 4
10 1
2 2
8 128
-1
Sample Output
12
7
512
3
255
分析
个人觉得这个题有很大的借鉴意义,一开始用的思路是简单模拟,用一个数组来模拟二叉树,小球往左走则 k x 2,往右走则 k x 2 + 1,然后改变节点的值;思路很简单清晰,但因计算量太大最终超时,这是原代码:
超时代码
#include <cstdio>
#include <iostream>
#include <cstring>
const int maxn = 1 << 20 - 1;
int tree[maxn];
int main() {
int T;
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
while (scanf("%d", &T) == 1 && T != -1) {
while (T--) {
int D, I;
scanf("%d%d", &D, &I);
memset(tree, 0, sizeof(tree));
for (int i = 1;;i++) {
int k = 1;
for (int j = 0;j < D - 1;j++) {
int p = k;
//printf("p=%d\n", p);
if (tree[k]) { k = 2 * k + 1; }
else { k = 2 * k; }
tree[p] = !tree[p];
}
if (i == I) { printf("%d\n", k); break; }
}
}
}
return 0;
}
然后看了紫书才发现这个问题的精髓,首先我们了解一个事实:
- 若有两个小球在同一个节点落下,那么这个节点恢复它原本的值。
根据上面的关系,可知在某一个节点落下的第 I 个小球在这个节点落下时,若 I 为奇数,则它应该向左边落下,同时它是下一个节点第 (I+1)/2 个落下的小球;若 I 为偶数,则它应该向右边落下,同时它是下一个节点第 I/2 个落下的小球。
如图,数字代表从根节点下落的小球标号,圆圈代表节点,圆圈旁边的数字个数即表明从这个节点落下的小球数目。
AC代码:
#include <cstdio>
#include <iostream>
#include <cstring>
int main() {
int T;
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
while (scanf("%d", &T)==1 && T != -1) {
while (T--) {
int D, I;
scanf("%d%d", &D, &I);
int k = 1;
for (int d = 0;d < D - 1;d++) {
if (I % 2) { k = k * 2;I = (I + 1) / 2; }
else { k = k * 2 + 1;I = I / 2; }
}
printf("%d\n", k);
}
}
return 0;
}