zoukankan      html  css  js  c++  java
  • UVa 10410

    题意

    给出一棵树的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;
    }
  • 相关阅读:
    html集合
    pyautocad
    CAD 批量提取点坐标,实现坐标的快速提取
    CAD
    python模块
    set,get,setter
    1 Http的表皮
    (6)小项目------完善增删改查的操作
    SSM学习笔记(6)---拦截器
    SSM学习笔记(5)-CGLIB动态代理
  • 原文地址:https://www.cnblogs.com/JinxiSui/p/9740592.html
Copyright © 2011-2022 走看看