Tree Reconstruction UVA - 10410
2017-08-03 14:43
281 查看
利用数组,首先记录BFS时每个节点的位置,然后利用栈,首先压入根节点的位置,对于后面读取的每个节点,如果是当前节点的子节点,那么位置之差至少为2(只考虑这种简单的情况,因为题目当中指出只要输出正确的情况之一即可),或者栈顶所表示的节点是根节点,那么就可以忽略位置的差值。同时注意,产生的树不一定必须是二叉树。具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;
int main(){
int n;
while (cin >> n){
int bfs[1010];
int dfs[1010];
vector<int> res[1010];
int root = 0;
for (int i = 1; i <= n; i++){
int x;
cin >> x;
bfs[x] = i;
}
cin >> root;
stack<int> s;
s.push(root);
for (int i = 1; i < n; i++){
int x;
cin >> x;
while (true){
int a = s.top();
if (a == root || bfs[x] > bfs[a] + 1){
s.push(x);
res[a].push_back(x);
break;
}
else s.pop();
}
}
for (int i = 1; i <= n; i++){
cout << i << ":";
for (int j = 0; j < res[i].size(); j++){
cout << " " << res[i][j];
}
cout << endl;
}
}
return 0;
}
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;
int main(){
int n;
while (cin >> n){
int bfs[1010];
int dfs[1010];
vector<int> res[1010];
int root = 0;
for (int i = 1; i <= n; i++){
int x;
cin >> x;
bfs[x] = i;
}
cin >> root;
stack<int> s;
s.push(root);
for (int i = 1; i < n; i++){
int x;
cin >> x;
while (true){
int a = s.top();
if (a == root || bfs[x] > bfs[a] + 1){
s.push(x);
res[a].push_back(x);
break;
}
else s.pop();
}
}
for (int i = 1; i <= n; i++){
cout << i << ":";
for (int j = 0; j < res[i].size(); j++){
cout << " " << res[i][j];
}
cout << endl;
}
}
return 0;
}
相关文章推荐
- uva10410 - Tree Reconstruction BFS和DFS重建树
- A - Tree Reconstruction UVA - 10410
- uva 548 Tree
- UVa 548 - Tree
- Tree Recovery-UVA 536
- UVA - 152 Tree's a Crowd
- UVA-12569 Planning mobile robot on Tree (EASY Version) (BFS+状态压缩)
- uva 10304 - Optimal Binary Search Tree
- uva 10304 - Optimal Binary Search Tree(区间dp)
- uva548 Tree
- UVa 10304 - Optimal Binary Search Tree
- Tree UVA 548(DFS)
- UVa10672 - Marbles on a tree(BFS)
- uva548 tree
- uva 548 tree
- UVa 10410 - Tree Reconstruction ( DFS, BFS, 栈 )
- Uva - 10410 - Tree Reconstruction
- S-Tree解题报告UVa 712二叉树/二分搜索
- uva 10304 Optimal Binary Search Tree(DP)
- 例题6-8 树 UVa 548 Tree