P1001A+Bproblem 学习笔记

· · 个人记录

Splay

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
inline void in(int &x){
    x=0;int f=1;char c=getchar();
    while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
    while(c>='0'&&c<='9')x=(x<<1)+(x<<3)+c-'0',c=getchar();
    x*=f;
}
const int N=100005;
int n,m,root,tot;
struct node{
    int fa,ch[2];
    int val,cnt,siz;
}a[N];
void Update(int x){//更新 
    if(x){
        a[x].siz=a[x].cnt;
        if(a[x].ch[0])a[x].siz+=a[a[x].ch[0]].siz;
        if(a[x].ch[1])a[x].siz+=a[a[x].ch[1]].siz;
    }
}
void Rotate(int x){//旋转 
    int fath=a[x].fa;
    int graf=a[fath].fa;
    bool flag=(a[fath].ch[1]==x);
    a[graf].ch[a[graf].ch[1]==fath]=x;
    a[x].fa=graf;
    a[fath].ch[flag]=a[x].ch[flag^1];
    a[a[x].ch[flag^1]].fa=fath;
    a[x].ch[flag^1]=fath;
    a[fath].fa=x;
    Update(fath);
    Update(x); 
}
void Splay(int x,int t){//将x旋转到t的子节点 
    while(a[x].fa!=t){
        int fath=a[x].fa;
        int graf=a[fath].fa;
        if(graf!=t)
            (a[graf].ch[0]==fath)^(a[fath].ch[0]==x)?Rotate(x):Rotate(fath);
        Rotate(x);
    }
    if(t==0)root=x;
}
void Find(int x){//寻找 
    int u=root;
    if(!u)return;
    while(a[u].ch[x>a[u].val]&&a[u].val!=x)
        u=a[u].ch[x>a[u].val];
    Splay(u,0); 
}
void Insert(int x){//插入 
    int u=root,fath=0;
    while(u&&a[u].val!=x){
        fath=u;
        u=a[u].ch[x>a[u].val];
    }
    if(u){
        a[u].cnt++;
        Update(u);
        Update(fath);
        Splay(u,0);
        return;
    }
    u=++tot;
    if(fath)
        a[fath].ch[x>a[fath].val]=u;
    a[u].ch[0]=a[u].ch[1]=0;
    a[u].fa=fath;
    a[u].val=x;
    a[u].cnt=1;
    a[u].siz=1;
    Splay(u,0);
}
int Find_pre_next(int x,int flag){//0为前驱,1为后继 
    Find(x);
    int u=root;
    if((a[u].val>x&&flag)||(a[u].val<x&&!flag))return u;
    u=a[u].ch[flag];
    while(a[u].ch[flag^1])
        u=a[u].ch[flag^1];
    return u;
}
void Delete(int x){//删除 
    int last=Find_pre_next(x,0);
    int next=Find_pre_next(x,1);
    Splay(last,0);
    Splay(next,last);
    int del=a[next].ch[0];
    if(a[del].cnt>1){
        a[del].cnt--;
        Splay(del,0);
    }
    else
        a[next].ch[0]=0;
}
int Find_rank(int x){//查询排名 
    int u=root,rnk=1;
    while(a[u].val!=x){
        if(x<a[u].val){
            u=a[u].ch[0];
            continue;
        }
        rnk+=a[a[u].ch[0]].siz+a[u].cnt;
        u=a[u].ch[1];
    }
    rnk+=a[a[u].ch[0]].siz;
    Splay(u,0);
    return rnk;//此处只将同值的算为一个 
}
int Find_kth(int x){//查询第K大的值 
    int u=root;
    if(a[u].siz<x||x<0)
        return 0;
    while(1){
        if(x>a[a[x].ch[0]].siz+a[u].cnt){
            x-=a[a[u].ch[0]].siz+a[u].cnt;
            u=a[u].ch[1];
        }
        else if(a[a[u].ch[0]].siz>=x)u=a[u].ch[0];
        else return a[u].val;
    }
}
int main(){
    int a,b;
    in(a);in(b);
    printf("%d\n",a+b);
    return 0;
}