UVA 712 S-Tree

题目链接: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.,以此类推。(这种方法更高效更易于理解)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值