习题6-11:树重建

习题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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值