Uva712 S树
Uva 712 S树
题目描述:
给出一棵满二叉树,每一层代表一个01变量,取0时往左走,取1时往右走。每层用一个变量\(x_i\)表示,那么这棵树可以等价于若干\(x_i\)之间的位运算,给出所有叶子节点的值以及一些查询(\(x_i\)的值),求每个查询到达的叶子节点的值。
题目链接:https://vjudge.net/problem/UVA-712
思路:
用到此前紫书的一个结论,即对一棵满二叉树编号,则节点k的左子节点和右子节点的编号分别为2k和2k+1。按照题目的输入格式,要确定每次查询的路径上,因为\(x_1,x_2,...,x_i\)出现的顺序不同,后面输入的查询路径就要相应地转换。这题我在输入上混着用getchar()
和cin
,写得有些繁琐,其实直接把每行当作string
读入就可以了。
代码:
#include <iostream>
#include <memory.h>
using namespace std;
const int maxn = 7 + 2;
int main()
{
int n;int kase = 0;
// freopen("uva712_in.txt", "r", stdin);
// freopen("uva712_out.txt", "w", stdout);
while(cin >> n && n){
int s[maxn], next[maxn];
int depth = n;
s[0] = 0, next[0] = 0;
int i = 1;
++kase;
printf("S-Tree #%d:\n", kase);
while(n--){
string str; cin >> str;
next[i] = next[i-1];
next[i-1] = str[1]-'0';
++i;
}
int terminal[1<<maxn];
memset(terminal, 0, sizeof(terminal));
char c; while((c=getchar()) == '\n');
for(int i = 0; i < 1<<depth; ++i){
terminal[i] = c - '0';
c = getchar();
}
int m; cin >> m;
int path[maxn], p[maxn];
while(m--){
int i = 0; char c;
memset(path, 0, sizeof(path));
memset(p, 0, sizeof(p));
while((c = getchar()) == '\n');
while(c != '\n'){
p[i] = c - '0';
++i;
c = getchar();
}
for(int i = 0; i < depth; ++i){
path[i] = p[next[i]-1];
}
int start = 1;
for(int i = 0; i < depth; ++i){
if(path[i]) start = start * 2 + 1;
else start = start * 2;
}
int end = start - (1 << depth);
cout << terminal[end];
}
cout << "\n" << "\n";
}
}