UVa 10410 - Tree Reconstruction ( DFS, BFS, 栈 )

题意

给出一棵树的BFS, DFS遍历 (扩展节点时按照编号从小到大访问)
求每个节点的子节点序列

思路

记录DFS序列中每个节点的位置, 由BFS得出两个节点的距离

如果距离为负, 说明既不是兄弟或孩子节点
如果距离为正且相邻, 说明是兄弟节点
如果距离为正但不相邻, 说明是孩子节点

处理递归过程

AC代码

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <stack>

using namespace std;

const int maxn = 1000 + 10;

vector<int> G[maxn];
int pos[maxn];
stack<int> s;

int main()
{
    int n, x;
    while( ~scanf("%d",&n) ){
        for( int i = 1; i <= n; i++ ){
            scanf("%d",&x);
            if( G[i].size() ) G[i].clear();
            pos[x] = i;
        }
        int root;
        scanf("%d",&root);
        while(!s.empty())  s.pop();
        s.push(root);
        for( int i = 1; i < n; i++ ){
            scanf("%d",&x);
            for(;;){
                int t = s.top();
                if(pos[t]+1 < pos[x] || t == root){
                    G[t].push_back(x);
                    s.push(x);
                    break;
                }
                else { s.pop(); }
            }
        }
        for( int i = 1; i <= n; i++ ){
            printf("%d:",i);
            int len = G[i].size();
            for( int j = 0; j < len; j++ )
                printf(" %d",G[i][j]);
            puts("");
        }
    }
    return 0;
}
posted @ 2018-03-08 18:03  JinxiSui  阅读(150)  评论(0编辑  收藏  举报