S-Trees poj1105(二叉树)

题目链接http://poj.org/problem?id=1105
题意:
给一个已知层数的满二叉树和每个叶子节点的值,(只有0,1),然后每个节点有两种选择,0是从该节点向左子树走,1是右子树,问给一串操作序列,每个操作序列都对应了底层的一个叶子节点,问这串操作序列得到的01串为多少

思路:
满二叉树的叶子节点个数为2的n次方个,所以,我们可以用一维数组去存储这些叶子节点,然后下标为0-2 ^ n -1;同时我们可以发现,将每个操作序列看作二进制并进行转换为10进制后,就是我们要得到的存储目标叶子节点值的下标号
所以,我们只需要把序列号转为10进制,再对应一维数组中下标即可

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>

using namespace std;

typedef long long ll;

const int maxn=500005;

int a[maxn],ans[maxn];
//ans存答案,a存从左到右每个叶子节点的值

int main()
{
    int cas = 0;
    int n;
    while(cin>>n,n){
        cas++;
       for(int i = 0; i < n; i++){
            char c;
            int x;
            cin>>c>>x;
       }
       for(int i = 0; i < pow(2,n); i++){
            scanf("%1d",&a[i]);
       }
       int m;
       cin>>m;
       for(int i = 0; i < m; i++){
            int sum = 0;
            for(int j = 1; j <= n; j++){
                int tp;
                scanf("%1d",&tp);
                if(tp){
                    sum += pow(2,n - j);
                }
            }
            ans[i] = a[sum];
       }
       cout<<"S-Tree #"<<cas<<":"<<endl;
       for(int i = 0; i < m; i++){
            cout<<ans[i];
       }
       cout<<endl<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值