#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<cstdio>
using namespace std;
const int maxn=500;
bool failed=false;
struct Node
{
bool have_value;
int v;
Node *left,*right;
Node():have_value(false),left(NULL),right(NULL){}
};
Node*root;
Node*newnode(){return new Node();}
void addnode(int v,char*s)
{
int n=strlen(s);
Node *u=root;
for(int i=0;i<n;i++)
if(s[i]=='L'){if(u->left==NULL)u->left=newnode();
u=u->left;}
else if(s[i]=='R'){if(u->right==NULL)u->right=newnode();u=u->right;}
if(u->have_value)failed=true;
u->v=v;
u->have_value=true;
}
bool bfs(vector<int>&ans)
{
queue<Node*>q;
ans.clear();
q.push(root);
while(!q.empty())
{
Node*u=q.front();
q.pop();
if(!u->have_value)return false;
ans.push_back(u->v);
if(u->left!=NULL)q.push(u->left);
if(u->right!=NULL)q.push(u->right);
}
return true;
}
void remove_tree(Node*u)
{
if(u==NULL)return;
remove_tree(u->left);
remove_tree(u->right);
delete u;
}
char s[maxn];
bool read_input()
{
failed=false;
remove_tree(root);
root=newnode();
for(;;)
{
if(scanf("%s",s)!=1)return false;
if(!strcmp(s,"()"))break;
int v;
sscanf(&s[1],"%d",&v);
addnode(v,strchr(s,',')+1);
}
return true;
}
int main()
{
vector<int>b;
read_input();
bfs(b);
if(failed||!bfs(b)){cout<<"-1";return 0;}
for(vector<int>::iterator it=b.begin();it!=b.end();it++)
cout<<*it<<" ";
}
//测试数据:
//输入:
//(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
//输出:5 4 8 11 13 4 7 2 1
//输入:(3,L) (4,R) ()
//输出:-1
//万事开头难,参考着紫书,看了一下午才把代码敲出来然后理解了整个程序的过程 题目是 UVa 122 小伙伴们不要直接拷贝我的代码,因为我的输入
//没有加循环语句,没法循环输入,想用的话自己加循环,这样可以强迫你去看代码的运行过程,嘿嘿嘿...
UVa 122 (紫书)
最新推荐文章于 2021-10-25 22:47:22 发布