• PAT甲级1135


    做出来了,但感觉心好痛。我发现我真是太懒惰了,以为简简单单记个模板,就万事大吉了。

    没想到自己的思维被模板固化,就不会根据实际情况作出相应的改变了。模板当然要记忆,

    但不可偷懒而导致思维僵化。引以为戒

    dfs为判断过程,是在求树高的基础上,增加一个参数,判断是否存在前一个为红色节点并且当前节点是红色的情况

    回溯判断当前节点的左右子树的黑高是否相等

    #include<cstdio>
    #include<algorithm>
    #include<cmath>
    //#define debug
    using namespace std;
    const int maxn=40;
    struct node{
        int data;
        int lc;
        int rc;
        node(){
            data=0;
            lc=rc=-1;
        }
    };
    bool cmp(int a,int b)
    {
        return abs(a)<abs(b);
    }
    int n;
    int ptr=0;
    node Tree[maxn];
    int pre[maxn];
    int in[maxn];
    void create(int &root,int preL,int preR,int inL,int inR)
    {
        if(preL>preR)return;
        if(preL>=n)return;
        int roote=pre[preL];
        root=ptr++;
        Tree[root].data=roote;
        int u=0;
        for(u=inL;u<=inR;u++){
            if(in[u]==roote)break;
        }
        int numLeft=u-inL;
        create(Tree[root].lc,preL+1,preL+numLeft,inL,u-1);
        create(Tree[root].rc,preL+numLeft+1,preR,u+1,inR);
    }
    bool IsRBt=true;
    int dfs(int root,int pren)
    {
        if(IsRBt==false)return -1;
        if(root==-1)return 1;
        if(pren<0&&Tree[root].data<0){
            IsRBt=false;
            return -1;
        }
        int lh=dfs(Tree[root].lc,Tree[root].data);
        int rh=dfs(Tree[root].rc,Tree[root].data);
        if(rh!=lh){
            IsRBt=false;
            return -1;
        }
        return Tree[root].data>0?max(lh,rh)+1:max(lh,rh);
    }
    int main()
    {
    #ifdef debug
        freopen("in.txt","r",stdin);
    #endif
        int t;
        node s;
        scanf("%d",&t);
        for(int i=0;i<t;i++){
            scanf("%d",&n);
            fill(Tree,Tree+maxn,s);
            ptr=0;
            IsRBt=true;
            for(int i=0;i<n;i++){
                scanf("%d",&pre[i]);
                in[i]=pre[i];
            }
            sort(in,in+n,cmp);
            int root;
            create(root,0,n-1,0,n-1);
            if(Tree[root].data<0)IsRBt=false;
            else
                dfs(root,Tree[root].data);
            if(IsRBt)printf("Yes
    ");
            else printf("No
    ");
        }
    #ifdef debug
        getchar();
    #endif
    }


  • 相关阅读:
    Python多线程join的用法
    Python多线程互斥锁
    python Queue模块
    精度计算————乘法(大数乘小数)
    精度计算——大数阶乘
    python埃式筛法求素数
    Scala io操作
    scala io,ubuntu常见配置
    大数据之scala高级语法学习
    大数据之scala基本语法学习
  • 原文地址:https://www.cnblogs.com/MalcolmMeng/p/8442969.html
Copyright © 2020-2023  润新知