UVa 10410 - Tree Reconstruction ( DFS, BFS, 栈 )
2018-03-08 18:03
211 查看
题意
给出一棵树的BFS, DFS遍历 (扩展节点时按照编号从小到大访问)求每个节点的子节点序列
思路
记录DFS序列中每个节点的位置, 由BFS得出两个节点的距离如果距离为负, 说明既不是兄弟或孩子节点
如果距离为正且相邻, 说明是兄弟节点
如果距离为正但不相邻, 说明是孩子节点
用栈处理递归过程
AC代码
#include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <stack> using namespace std; const int maxn = 1000 + 10; vector<int> G[maxn]; int pos[maxn]; stack<int> s; int main() { int n, x; while( ~scanf("%d",&n) ){ for( int i = 1; i <= n; i++ ){ scanf("%d",&x); if( G[i].size() ) G[i].clear(); pos[x] = i; } int root; scanf("%d",&root); while(!s.empty()) s.pop(); s.push(root); for( int i = 1; i < n; i++ ){ scanf("%d",&x); for(;;){ int t = s.top(); if(pos[t]+1 < pos[x] || t == root){ G[t].push_back(x); s.push(x); break; } else { s.pop(); } } } for( int i = 1; i <= n; i++ ){ printf("%d:",i); int len = G[i].size(); for( int j = 0; j < len; j++ ) printf(" %d",G[i][j]); puts(""); } } return 0; }
相关文章推荐
- [UVA10410]Tree Reconstruction[BFS、DFS序建树]
- 用bfs和dfs建树--uva10410 Tree reconstruction
- uva10410 - Tree Reconstruction BFS和DFS重建树
- UVA10410 TreeReconstruction 树重建 (dfs,bfs序的一些性质,以及用栈处理递归 )
- UVA 1600 - Patrol Robot( BFS & DFS)
- 搜索(DFS+BFS)——UVA Live 6455
- UVA 11882 Biggest Number (搜索+剪枝(dfs+bfs))
- UVA1423Guess (dfs,bfs拓扑排序)
- UVALive - 6455 Stealing Harry Potter's Precious (bfs+dfs)
- XYZZY uva 10557 -BFS+DFS判断
- UVA 439 Knight Moves --DFS or BFS
- uva 10557 XYZZY(DFS+BFS)
- UVA - 572 Oil Deposits(DFS和BFS两种解法)
- uva10557 - XYZZY(图的bfs ;dfs)
- UVa 572 - Oil Deposits解题报告(图的DFS和BFS)
- 图-用DFS求连通块- UVa 1103和用BFS求最短路-UVa816。
- UVA - 10004 Bicoloring (dfs和bfs两种解法)
- Uva11882 Biggest Number 【dfs回溯+bfs剪枝】【习题7-15】
- UVA 657 The die is cast ——bfs+dfs
- XYZZY uva BFS+DFS