您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: