zoukankan      html  css  js  c++  java
  • PAT (Advanced Level) 1020. Tree Traversals (25)

    递归建树,然后BFS一下

    #include<iostream>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #include<cstdio>
    #include<queue>
    #include<vector>
    using namespace std;
    
    const int maxn=40;
    int a[maxn],b[maxn];
    int n,tot;
    struct Node
    {
        int left;
        int right;
        int val;
    }node[maxn];
    
    void build(int L,int R,int fa,int f)
    {
        int P=-1;
        for(int i=L;i<=R;i++)
            for(int j=1;j<=n;j++)
                if(b[i]==a[j]) P=max(P,j);
    
        int root_val=a[P];
    
        if(tot==0)
        {
            ++tot;
            node[tot].val=root_val;
        }
        else if(f==0)
        {
            ++tot;
            node[tot].val=root_val;
            node[fa].left=tot;
        }
        else if(f==1)
        {
            ++tot;
            node[tot].val=root_val;
            node[fa].right=tot;
        }
    
        int tmp=tot;
    
        for(int i=L;i<=R;i++)
        {
            if(b[i]==root_val)
            {
                if(i-L>0) build(L,i-1,tmp,0);
                if(R-i>0) build(i+1,R,tmp,1);
                break;
            }
        }
    
    }
    
    void bfs()
    {
        queue<int>Q;
        Q.push(1);
        int cnt=0;
        while(!Q.empty())
        {
            int head=Q.front(); Q.pop();
            printf("%d",node[head].val); cnt++;
            if(cnt<n) printf(" ");
            else printf("
    ");
            if(node[head].left!=-1) Q.push(node[head].left);
            if(node[head].right!=-1) Q.push(node[head].right);
        }
    }
    
    int main()
    {
        scanf("%d",&n); tot=0;
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);
        for(int i=1;i<=n;i++) scanf("%d",&b[i]);
        for(int i=0;i<=30;i++) node[i].left=node[i].right=-1;
        build(1,n,-1,-1);
        bfs();
        return 0;
    }
  • 相关阅读:
    NOIP2018 游记
    HDU1556 敌兵布阵
    BZOJ 1032 [JSOI2007]祖码Zuma
    BZOJ 1068 [SCOI2007]压缩
    BZOJ 1090 [SCOI2003]字符串折叠
    BZOJ 1260 [CQOI2007]涂色paint
    BZOJ 1055 [HAOI2008]玩具取名
    HDU 5151 Sit sit sit
    HDU 4283 You Are the One
    vue系列8:webpack
  • 原文地址:https://www.cnblogs.com/zufezzt/p/5499430.html
Copyright © 2011-2022 走看看