题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=653
题目(输入):
3 (depth)
x3 x1 x2 (二叉树从上到下每一层的变量)
00000111 (叶子结点从左到右的值)
4 (表示需要走几次二叉树,m)
001 (表示x1=0,x2=0,x3=0 变量为0时往左走,变量为1时往右走)
......
当depth输入为0时结束输入。
通过二叉树可以发现通过一种路径所到达的叶子结点的下标(用一个数组来保存叶子结点的值)与路径之间存在着一定的关系,(用一个数组series来保存每到一层所表示的叶子结点下标的变化)假设在深度为curdepth时能达到的叶子结点下标为series[curdepth],根节点深度为0,series[0]=0, 当该节点的变量值为0时往左走,叶子结点下标不变,即series[curdepth+1]=series[curdepth],当为1时往右走,series[curdepth+1]=series[curdepth]+pow(2,depth-curdepth-1);最后所能到达的叶子结点为child[series[depth]];
AC代码:
#include <cstdio> #include <cstdlib> #include <cmath> #include<cstring> using namespace std; const int maxn = (1 << 8 - 1); const int sizes = 10; int k = 1; int main() { int depth; while (scanf("%d", &depth) == 1 && depth) { char res[sizes];//保存结果 int ordering[sizes];//二叉树的变量顺序,每一层为同一个变量,顺序指从上到下 memset(res, '\0', sizes); char child[maxn];//叶子结点的值 int i = 0; for (i; i < depth; i++) { getchar();//吃掉变量名字以前多于的符号 scanf("%*c%d",&ordering[i]); } getchar();//吃掉换行符 scanf("%s", child); int m; scanf("%d", &m); for(i=0;i<m;i++) { int series[sizes]; //保存到达每一层时所能到达的节点编号 series[0] = 0; char x[sizes];//保存路径 getchar(); scanf("%s", x+1); for (int j = 0; j <depth; j++) { if (x[ordering[j]] == '0') series[j+1] = series[j]; else series[j + 1] = series[j] + (int)pow(2, depth - j - 1); } res[i] = child[series[depth]] ; } printf("S-Tree #%d:\n%s\n\n",k++, res); } return 0; } |
第二种解法:
运用二进制计算,当路径为001时,对应叶子结点下标为1.,以此类推。(这种方法更高效更易于理解)