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;
    }
  • 相关阅读:
    js实现点击上下按钮,图片向上向下循环滚动切换
    jquery实现点击进入新的页面。(jquery实现超链接)
    jquery实现鼠标移入移除背景图片切换
    C:WindowsSystem32driversetchosts文件显示
    网页添加qq咨询
    本地虚拟站点创建
    ftp获取mysql数据库方法
    数论基础
    最小费用最大流
    AC自动机 hdu2222
  • 原文地址:https://www.cnblogs.com/itcsl/p/9179563.html
Copyright © 2011-2022 走看看