zoukankan      html  css  js  c++  java
  • 【二叉搜索树】poj 1577 Falling Leaves

    http://poj.org/problem?id=1577

    【题意】

    有一颗二叉搜索树,每次操作都把二叉搜索树的叶子从左到右揪掉(露出来的父节点就变成了新的叶子结点)

    先给出了揪掉的叶子序列(多个字符串)

    给出这课二叉搜索树先序遍历的结果

    【思路】

    最后揪掉的肯定是根,最后揪掉的是最先插入的,倒着建立二叉搜索树就可以。

    【AC】

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<algorithm>
    #include<queue>
    
    using namespace std;
    struct node{
        int num;
        node *lef;
        node *rig;
    };
    const int maxn=1e3+2;
    string str[maxn];
    int cur;
    
    node *work(){
        node *rt=(node *)malloc(sizeof(node));
        rt->num=str[cur-1][0]-'A';
        rt->lef=NULL;
        rt->rig=NULL;
        for(int i=cur-2;i>=0;i--){
            int len=str[i].length();
            for(int j=0;j<len;j++){
                node *now=rt;
                while(1){
                    if(str[i][j]-'A'<now->num){
                        if(now->lef) now=now->lef;
                        else{
                            node *nd=(node *)malloc(sizeof(node));
                            nd->num=str[i][j]-'A';
                            nd->lef=NULL;
                            nd->rig=NULL;
                            now->lef=nd;
                            break;
                        }
                    }else{
                        if(now->rig) now=now->rig;
                        else{
                            node *nd=(node *)malloc(sizeof(node));
                            nd->num=str[i][j]-'A';
                            nd->lef=NULL;
                            nd->rig=NULL;
                            now->rig=nd;
                            break;
                        }
                    }
                }
            }
        }
        return rt;
    }
    void preorder(node *rt){
        if(rt==NULL) return;
        printf("%c",rt->num+'A');
        preorder(rt->lef);
        preorder(rt->rig);
        free(rt);
    }
    int main(){
        cur=0;
        while(cin>>str[cur]){
            if(str[cur][0]=='*'||str[cur][0]=='$'){
                node *rt=work();
                preorder(rt);
                puts("");
                if(str[cur][0]=='$') break;
                else cur=0;
            }else{
                cur++;
            }
        }
        return 0;
    }
  • 相关阅读:
    常见linux内核线程说明
    /proc/modules分析
    linux用户空间和内核空间(内核高端内存)_转
    二层交换机/三层交换机/路由器
    NAT--Network Address Translator
    curl命令使用
    (转)XML中必须进行转义的字符
    LFCP
    IPSP问题
    API和schema开发过程问题汇总
  • 原文地址:https://www.cnblogs.com/itcsl/p/9179563.html
Copyright © 2011-2022 走看看