S-Trees UVA - 712

这个题形如二叉树,但我没有建树,用了类似于中找到对应叶子位置的方法。本题中,非终止的层数有几层,则叶子数为1<<n,后续输入的4个查询,我按照根据输入的查询来找到应该的叶子的位置,例如:输入时是x1,x2,x3, 4次查询是000 010 111 110,则对应叶子的位置是0,2,7,6.对应叶子的值就是0 0 1 1.

可能大神们有更好的方法,我这个方法有点繁琐。下面是代码,因为我一个一个的读入,所以要吃掉很多回车。

/*************************************************************************
      > File Name: S-Trees UVA - 712
      > Author: Mrhanice
      > Mail: 690697134@qq.com
      > Created Time: 20170311
      > link : https://vjudge.net/problem/UVA-712
  ************************************************************************/
#include <cstdio>
#include <iostream>
#include <sstream>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
using namespace std;

const int maxn=1<<10;
int main()
{
    int t,cnt=0;
    while(scanf("%d",&t)==1&&t)
    {
        getchar();//吃回车
        vector <int> ve;
        int x;
        string var;
        getline(cin,var);
        for(int i=0;i<var.size();i++)
        {
            if(var[i]=='x') var[i]=' ';//把x都变成空格;
        }
        stringstream line(var);
        while(line >> x) ve.push_back(x);//存的是每层上的xn的顺序,为了方便后面的映射
        int leaf[maxn];
        for(int i=0;i<(1<<t);i++)
        {
            int c=getchar();
            leaf[i]=c-'0';
        }
        getchar();//吃回车;
        queue <int> q;//用来存储每次按编号找得到的叶子值,就是不同的0,1值
        int n;
        cin >> n;
        getchar();
        while(n--)
        {
           int vva[t];
           map <int ,int > m;
           for(int i=0;i<t;i++)
           {
               int c=getchar();
               vva[i]=c-'0';
               m[i+1]=vva[i];
           }
           getchar();
           int sum=0,target;
           for(int i=0;i<ve.size();i++)
           {
               sum=sum*2+m[ve[i]];//计算出编号是第几个叶子。
           }
           target=leaf[sum];
           q.push(target);
        }
        printf("S-Tree #%d:\n",++cnt);
        while(!q.empty())
        {
            cout << q.front();
            q.pop();//输出队列中的元素。
        }
        cout << endl << endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值