您的位置:首页 > 其它

UVa 122 - Trees on the level

2014-11-20 11:24 441 查看
总算学到树了,是道BFS的题。可以用指针+结构体,但是不喜欢,所以按书上的改成了数组。思路和书上的一样。

#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn=550;
const int root=1;
int cnt,left[maxn],right[maxn],value[maxn];
bool failed,have_value[maxn];
char s[maxn];
vector<int>a;
void new_tree(){
left[root]=right[root]=0;
have_value[root]=false;
cnt=root;
return;
}
int newnode(){
int u=++cnt;
left[u]=right[u]=0;
have_value[u]=false;
return u;
}
void addnote(int v,char* s){
int n=(int)strlen(s);
int u=root;
for(int i=0;i<n;i++)
if(s[i]=='L'){
if(!left[u]) left[u]=newnode();
u=left[u];
}
else if(s[i]=='R'){
if(!right[u]) right[u]=newnode();
u=right[u];
}
if(have_value[u]) failed=true;
value[u]=v;
have_value[u]=true;
return;
}
bool read_input(){
failed=false;
for(;;){
if(scanf("%s",s)!=1) return false;
if(!strcmp(s,"()")) break;
int v;
sscanf(&s[1],"%d",&v);
addnote(v,strchr(s,',')+1);
}
return true;
}
bool bfs(){
if(failed) return false;
queue<int>q;
a.clear();
q.push(root);
while(!q.empty()){
int u=q.front();
q.pop();
if(!have_value[u]) return false;
a.push_back(value[u]);
if(left[u]) q.push(left[u]);
if(right[u]) q.push(right[u]);
}
return true;
}
void print(){
for(int i=0;i<a.size();i++){
if(i) printf(" ");
printf("%d",a[i]);
}
printf("\n");
return;
}
int main(){
while(1){
new_tree();
if(!read_input()) break;
if(!bfs()) failed=true;
if(failed) printf("not complete\n");
else print();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: