习题6-11:树重建
题目大意:
给定一个树的BFS和DFS,求这棵树。
解题思路:
用栈维护即可。对应BFS序列映射出了每个节点和根节点的距离,遍历dfs序列,对当前节点和栈顶节点比较,如果该节点距离根节点更远,则说明该节点为栈顶节点个孩子节点,则记录后将节点放入栈中。否则弹掉栈顶元素继续比较。需要注意一点,即当元素与栈顶元素的距离值大1的时候要视为相等,因为它们属于兄弟节点(答案给出任一种情况就行)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<queue>
#include<map>
#include<stack>
#include<vector>
#include<list>
#include<deque>
using namespace std;
typedef long long ll;
const int maxn = 1e3 + 10;
const double eps = 1e-6;
const int INF = 1 << 30;
int T, n, m;
int dis[maxn];
vector<int>son[maxn];
int main()
{
while(scanf("%d", &n)!=EOF)
{
int x;
for(int i = 1; i <= n; i++)
{
scanf("%d",&x);
dis[x] = i;
son[i].clear();
}
int root;
stack<int>tree;
cin >> root;
tree.push(root);
for(int i = 1; i < n; i++)
{
scanf("%d",&x);
while(1)
{
int u = tree.top();
if(u == root || dis[u] + 1 < dis[x])
{
son[u].push_back(x);
tree.push(x);
break;
}
else tree.pop();
}
}
for(int i = 1; i <= n; i++)
{
printf("%d:",i);
for(int j = 0; j < son[i].size(); j++)
cout<<" "<<son[i][j];
cout<<endl;
}
}
return 0;
}