Tree Reconstruction UVA - 10410

29 篇文章 0 订阅
14 篇文章 0 订阅

UVA-10410

题目:给一棵树的BFS,DFS的遍历序列,求这棵树每个结点的子结点。

思路:(看了无数大佬们的题解,才想明白一些问题)

         这个题考察了对BFS、DFS遍历的理解。

         设定BFS[i]来表示结点i在BFS中的出现下标。如果BFS[u] + 1 < BFS[v]说明结点v在BFS序列中不紧贴着u,且在u后部,则v一定是u的子结点。

         DFS序列是到叶结点才返回上一层的。

        详情见代码。

#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<sstream>
#include<map>
#include<stack>
#include<queue>
#include<set>
#include<string>
using namespace std;
int n,BFS_list[1001],Position[1001];
vector<int> son[1001];
int main(){
    while(scanf("%d",&n)!=EOF){
        for(int i = 1;i<=n;i++){
            scanf("%d",&BFS_list[i]);
            Position[BFS_list[i]] = i; //保存结点在BFS中的位置
            son[BFS_list[i]].clear();
        }
        int x,root;
        scanf("%d",&root);
        stack<int> save;
        save.push(root);
        for(int i = 2;i<=n;i++){
            scanf("%d",&x);
            int Wait_To_Explore;
            while(true){
                Wait_To_Explore = save.top(); //准备找儿子的结点
                if(Wait_To_Explore == root||Position[Wait_To_Explore] + 1 < Position[x]){//如果(Wait_To_Explore为根节点) 或 (x点在BFS序列中不紧贴,且在 Wait_To_Explore 后,则x为其子结点)
                    son[Wait_To_Explore].push_back(x);
                    save.push(x);//当前x入栈,进入下一次被找儿子的队伍中
                    break;
                }else{
                    save.pop();//如果当前Wait_To_Explore不满足上述条件,则说明x不是Wait_To_Explore的子结点,应是Wait_To_Explore父(或 祖父...Root)结点的其他子结点。则可以说明当前的Wait_To_Explore已经是树叶了,DFS已经完成了对其的拓展,则其出栈。
                }
            }
        }
        for(int i = 1;i<=n;i++){
            printf("%d:",i);
            sort(son[i].begin(),son[i].end());
            for(int j = 0;j<son[i].size();j++){
                printf(" %d",son[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值