• UVA.548 Tree(二叉树 DFS)


    UVA.548 Tree(二叉树 DFS)

    题意分析

    给出一棵树的中序遍历和后序遍历,从所有叶子节点中找到一个使得其到根节点的权值最小。若有多个,输出叶子节点本身权值小的那个节点。
    先递归建树,然后DFS求解。

    代码总览

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <string>
    #include <sstream>
    #include <queue>
    #include <stack>
    #include <set>
    #include <map>
    #include <vector>
    #define nmax 100000
    #define INF 0x3f3f3f3f
    using namespace std;
    int inorder[nmax],postorder[nmax];
    int lnode[nmax],rnode[nmax];
    int i;
    bool read_input()
    {
        memset(inorder,0,sizeof(inorder));
        memset(postorder,0,sizeof(postorder));
        string s;
        if(!getline(cin,s)) return false;
        else{
            stringstream ss(s);
            i = 0;
            int x;
            while(ss >> x) inorder[i++] = x;
            getline(cin,s);
            stringstream sss(s);
            i = 0;
            while(sss>>x) postorder[i++] = x;
        }
        return true;
    }
    // 递归建树
    int buildtree(int l1,int r1, int l2, int r2)
    {
        if(l1>r1) return 0;
        int root = postorder[r2];
        int p = l1;
        while(inorder[p] != root) p++;
        int cnt = p-l1;
        lnode[root] = buildtree(l1,p-1,l2,l2+cnt-1);
        rnode[root] = buildtree(p+1,r1,l2+cnt,r2-1);//
        return root;
    }
    int bestsum,best;
    void dfs(int u, int sum)
    {
        sum+=u;
        if(!lnode[u] && !rnode[u])
            if(sum<bestsum || (sum == bestsum && u<best)){
                best = u;
                bestsum = sum;
            }
        if(lnode[u]) dfs(lnode[u],sum);
        if(rnode[u]) dfs(rnode[u],sum);
    }
    int main()
    {
        //freopen("in.txt","r",stdin);
        while(read_input()){
            bestsum = INF;best = INF;
            buildtree(0,i-1,0,i-1);
            dfs(postorder[i-1],0);
            cout<<best<<"
    ";
        }
        return 0;
    }
  • 相关阅读:
    舌尖上的中关村
    解决winform窗体闪烁问题
    24段魔尺,可以折出哪些精美图案(续)
    24段魔尺,可以折出哪些精美图案
    关于Python编程的一些问答
    BZOJ 1025: [SCOI2009]游戏
    BZOJ 1025: [SCOI2009]游戏
    BZOJ 1207: [HNOI2004]打鼹鼠
    BZOJ 1207: [HNOI2004]打鼹鼠
    BZOJ 1046: [HAOI2007]上升序列
  • 原文地址:https://www.cnblogs.com/pengwill/p/7367121.html
Copyright © 2020-2023  润新知