zoukankan      html  css  js  c++  java
  • UVA 10410 Tree Reconstruction (树重建)

    题意:给定一个树的bfs和dfs序列,升序输出每个结点的子结点列表。

    分析:因为建树不唯一,假定若bfs[u] = bfs[v] + 1,则u是v的兄弟结点,否则是孩子结点。用栈维护。

    #pragma comment(linker, "/STACK:102400000, 102400000")
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<cmath>
    #include<iostream>
    #include<sstream>
    #include<iterator>
    #include<algorithm>
    #include<string>
    #include<vector>
    #include<set>
    #include<map>
    #include<stack>
    #include<deque>
    #include<queue>
    #include<list>
    #define Min(a, b) ((a < b) ? a : b)
    #define Max(a, b) ((a < b) ? b : a)
    typedef long long ll;
    typedef unsigned long long llu;
    const int INT_INF = 0x3f3f3f3f;
    const int INT_M_INF = 0x7f7f7f7f;
    const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
    const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f;
    const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
    const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
    const int MOD = 1e9 + 7;
    const double pi = acos(-1.0);
    const double eps = 1e-8;
    const int MAXN = 1000 + 10;
    const int MAXT = 10000 + 10;
    using namespace std;
    int id[MAXN];
    stack<int> s;
    set<int> son[MAXN];
    int main(){
        int n;
        while(scanf("%d", &n) == 1){
            while(!s.empty()) s.pop();
            memset(id, 0, sizeof id);
            for(int i = 0; i < MAXN; ++i) son[i].clear();
            int x;
            for(int i = 1; i <= n; ++i){
                scanf("%d", &x);
                id[x] = i;
            }
            int root;
            scanf("%d", &root);
            s.push(root);
            for(int i = 2; i <= n; ++i){
                scanf("%d", &x);
                while(1){
                    int t = s.top();
                    if(t == root || id[x] > id[t] + 1){
                        son[t].insert(x);
                        s.push(x);
                        break;
                    }
                    else s.pop();
                }
            }
            for(int i = 1; i <= n; ++i){
                printf("%d:", i);
                for(set<int>::iterator it = son[i].begin(); it != son[i].end(); ++it){
                    cout << " " << *it;
                }
                printf("\n");
            }
        }
        return 0;
    }
  • 相关阅读:
    c实现二叉树
    C实现栈与队列
    c的链表实现
    LB_Keogh
    LB_Yi
    LB_Kim
    Lab7:同步互斥
    Lab6:进程的调度
    Lab45:进程和线程
    Lab3:虚拟内存管理
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/6285226.html
Copyright © 2011-2022 走看看