• 白书上的Treap模板


    改良

    #include <iostream>
    #include <ctime>
    #include <cstdlib>
    #define MAX 100
    using namespace std;
    
    const int MAX_NODE=100;
    struct Node{
        Node* ch[2];//左右子树
        int fix;//优先级。数值越大,优先级越高
        int key;
        int size;//以它为根的子树的总结点数
        bool operator<(const Node& rhs) const {
            return key<rhs.key;
        }
        int cmp(int x) const{
            if (x==key) return -1;
            return x<key?0:1;
        }
        //名次树
        void maintain(){
            size=1;
            if (ch[0]!=NULL) size+=ch[0]->size;
            if (ch[1]!=NULL) size+=ch[1]->size;
        }
    };
    
    struct Treap{
        Node nodePool[MAX_NODE],*cur;
        Node* root;
        Treap(){
            srand(time(0));
            cur=nodePool;
            root=NULL;
        }
        void clear(){
            srand(time(0));
            cur=nodePool;
            root=NULL;
        }
        Node* newNode(){
            Node* t=cur++;
            return t;
        }
        //d=0代表左旋,d=1代表右旋
        void rotate(Node* &o,int d){
            Node* k=o->ch[d^1];
            o->ch[d^1]=k->ch[d];
            k->ch[d]=o;
            o->maintain();
            k->maintain();
            o=k;
        }
        //在以o为根的子树中插入键值x,修改o
        void insert(Node* &o,int x){
            if (o==NULL){
                o=newNode();
                o->ch[0]=o->ch[1]=NULL;
                o->key=x;
                o->fix=rand();
            }
            else
            {
                int d=o->cmp(x);
                if (d!=-1){
                    insert(o->ch[d],x);
                    if (o->ch[d]>o) rotate(o,d^1);
                }
            }
        }
        void remove(Node* &o,int x){
            int d=o->cmp(x);
            if (d==-1){
                if (o->ch[0]==NULL) o=o->ch[1];
                else if (o->ch[1]==NULL) o=o->ch[0];
                else{
                    int d2=(o->ch[0]>o->ch[1]?1:0);
                    rotate(o,d2);
                    remove(o->ch[d2],x);
                }
            }
            else remove(o->ch[d],x);
        }
        bool find(Node* o,int x){
            while (o!=NULL){
                int d=o->cmp(x);
                if (d==-1) return 1;
                else o=o->ch[d];
            }
            return 0;
        }
    };
    





  • 相关阅读:
    Hbase 命令小结
    shell while内获取外部变量内容
    Idea的live template参数中的预定义功能
    Adobe Illustrator里使用fontawesome矢量图标
    五笔结构与识别码
    致第一次安装RIME的你
    sublime Text Pastry使用
    PHOTOSHOP CC 2015插件安装方法
    搭建自己的OpenWrt开发环境
    【OpenWRT】 Chaos Calmer 15.05 编译
  • 原文地址:https://www.cnblogs.com/cyendra/p/3681596.html
Copyright © 2020-2023  润新知