• pat 甲级 1086(树的遍历||建树)


    思路1:可以用建树来做

    由于是先序遍历,所以直接先序建树就行了。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int maxn = 12000;
    int a[maxn],n,num;
    char str[20];
    void build(int id)
    {
        int x;
        if(num<=0) return ;
        scanf("%s",str);
        if(str[1]=='u')
        {
            scanf("%d",&x);
            a[id]=x;
            num--;
            build(id*2);
            build(id*2+1);
        }
        else num--;
    }
    void postorder(int x)
    {
        if(a[x]!=0)
        {
            postorder(x*2);
            postorder(x*2+1);
            if(num==0) printf("%d",a[x]),num=1;
            else printf(" %d",a[x]);
        }
    }
    int main(void)
    {
        int i;
        cin>>n;
        getchar();
        num=n*2;
        build(1);
        num=0;
        postorder(1);
        return 0;
    }
    View Code

    思路2:转换为前序中序遍历(参考柳神的博客)

    如果输入时不带堆栈就是前序遍历,带堆栈就是中序遍历,最后转换为后序遍历。

    #include<iostream>
    #include<vector>
    #include<cstdio>
    #include<stack>
    #include<cstring>
    using namespace std;
    const int maxn = 12000;
    vector <int> in,pre,num;
    char str[20];
    int n,pt=0;
    void f(int root,int st,int ed)
    {
        if(st>ed) return ;
        int i;
        for(i=st;i<=ed;i++) if(pre[root]==in[i]) break;
        f(root+1,st,i-1);
        f(root+(i-st)+1,i+1,ed);
        if(pt==0) printf("%d",num[pre[root]]),pt=1;
        else printf(" %d",num[pre[root]]);
    }
    int main(void)
    {
        int i,x,id=0;
        stack <int> st;
        cin>>n;
        for(i=0;i<n*2;i++)
        {
            scanf("%s",str);
            if(str[1]=='u')
            {
                scanf("%d",&x);
                num.push_back(x);
                pre.push_back(id);
                st.push(id++);
            }
            else
            {
                in.push_back(st.top());
                st.pop();
            }
        }
        f(0,0,n-1);
        return 0;
    }
    View Code
  • 相关阅读:
    第七章习题G题
    第二周习题O题
    P4735 最大异或和
    P3008 [USACO11JAN]道路和飞机Roads and Planes
    P4009 汽车加油行驶问题
    P1073 最优贸易
    P2260 [清华集训2012]模积和
    P2865 [USACO06NOV]路障Roadblocks
    P1821 [USACO07FEB]银牛派对Silver Cow Party
    P4180 【模板】严格次小生成树[BJWC2010]
  • 原文地址:https://www.cnblogs.com/2018zxy/p/10079680.html
Copyright © 2020-2023  润新知