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;
}