题目链接:Tree Reconstruction
题目大意:给定一棵树的DFS序和BFS序,求这棵树。
解题思路:先跑一遍BFS,并将每个节点映射成BFS序,由于BFS的特性,其序号越大,离根结点的距离相等或更远。接着遍历DFS序,并用栈维护结点之间的关系,若当前序号比栈顶元素大,则该结点为孩子结点,否则pop掉栈顶元素继续与下一个元素比较。由于只告诉BFS和DFS序所建立的树并不唯一,所以我们强制认为只比当前结点序号大1的结点为该结点的兄弟结点。
代码如下:
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 2e4 + 15;
int pos[1005];
int main(){
ios::sync_with_stdio(false);
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif
int n, node, root;
while(cin >> n){
vector<int> chd[1005];
for(int i = 1; i <= n; i++){
cin >> node;
pos[node] = i;
}
cin >> node;
stack<int> sta;
sta.push(node);
root = node;
for(int i = 2; i <= n; i++){
cin >> node;
while(1){
int e = sta.top();
if(e == root || pos[node] > pos[e] + 1){
chd[e].push_back(node);
sta.push(node);
break;
}
else
sta.pop();
}
}
for(int i = 1; i <= n; i++){
cout << i << ":";
for(auto e : chd[i]){
cout << ' ' << e;
}
cout << endl;
}
}
return 0;
}