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; }
相关文章推荐
- UVa 122 - Trees on the level
- UVA - 122 Trees on the level Map
- UVA122 Trees on the level【二叉树】【BFS】
- UVa 122 (二叉树的层次遍历) Trees on the level
- uva122 trees on the level
- uva 122 - Trees on the level
- UVa 122 - Trees on the level
- Uva-122 - Trees on the level(二叉树与set)
- UVa 122 - Trees on the level【二叉树初接触(BFS)】
- UVA - 122 Trees on the level
- Uva - 122 - Trees on the level
- UVa 122 Trees on the level(二叉树层次遍历)
- UVA_122: Trees on the level
- UVA 122 - Trees on the level
- uva 122 Trees on the level
- uva 122 - Trees on the level(一棵看着书都写不利索的树……)
- UVA - 122 Trees on the level
- uva122 Trees on the level(锻炼指针建一棵二叉树)
- 例题6-7 UVa122 Trees on the level(树&&队列BFS&&sscanf字符串转整数)
- Uva - 122 - Trees on the level