zoukankan      html  css  js  c++  java
  • 【模板】splay维护序列

    题目大意:维护一个长度为 N 的序列,支持单点插入,单点询问。

    注意事项如下:

    • build 函数中要记得初始化 fa。
    • 插入两个端点值。

    代码如下

    #include <bits/stdc++.h>
    #define pb push_back
    #define mp make_pair
    #define all(x) x.begin(),x.end()
    using namespace std;
    typedef long long ll;
    const int inf=0x3f3f3f3f;
    const int maxn=1e5+10;
    
    inline int read(){
    	int x=0,f=1;char ch;
    	do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    	do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    	return f*x;
    }
    
    int n,m,a[maxn];
    struct node{
    	#define ls(x) t[x].ch[0]
    	#define rs(x) t[x].ch[1]
    	int ch[2],fa,val,size;
    }t[maxn<<1];
    int tot,root;
    inline void pushup(int o){t[o].size=t[ls(o)].size+t[rs(o)].size+1;}
    inline bool get(int o){return o==rs(t[o].fa);}
    inline void rotate(int o){
    	int fa=t[o].fa,gfa=t[fa].fa,d1=get(o),d2=get(fa);
    	t[fa].ch[d1]=t[o].ch[d1^1],t[t[o].ch[d1^1]].fa=fa;
    	t[fa].fa=o,t[o].ch[d1^1]=fa;
    	t[o].fa=gfa,t[gfa].ch[d2]=o;
    	pushup(fa),pushup(o);
    }
    inline void splay(int o,int goal){
    	while(t[o].fa!=goal){
    		int fa=t[o].fa,gfa=t[fa].fa;
    		if(gfa!=goal)get(fa)==get(o)?rotate(fa):rotate(o);
    		rotate(o);
    	}
    	if(!goal)root=o;
    }
    int find(int o,int k){
    	if(k<=t[ls(o)].size)return find(ls(o),k);
    	else if(k>t[ls(o)].size+1)return find(rs(o),k-t[ls(o)].size-1);
    	else return o;
    }
    int build(int fa,int l,int r){
    	if(l>r)return 0;
    	int o=++tot;
    	int mid=l+r>>1;
    	t[o].val=a[mid],t[o].fa=fa;
    	ls(o)=build(o,l,mid-1),rs(o)=build(o,mid+1,r);
    	return pushup(o),o;
    }
    void insert(int pos,int val){
    	int x=find(root,pos-1),y=find(root,pos);
    	splay(x,0),splay(y,x);
    	++tot,t[tot].val=val,t[tot].size=1,t[tot].fa=y,ls(y)=tot;
    	pushup(y),pushup(x);
    }
    
    void read_and_parse(){
    	n=m=read();
    	for(int i=2;i<=n+1;i++)a[i]=read();
    	root=build(0,1,n+2);
    }
    void solve(){
    	while(m--){
    		int opt=read(),l=read(),r=read(),c=read();
    		if(opt==0)insert(l+1,r);
    		else if(opt==1)printf("%d
    ",t[find(root,r+1)].val);
    	}
    }
    int main(){
    	read_and_parse();
    	solve();
    	return 0;
    }
    
    
  • 相关阅读:
    指针如何影响结构体,细节的思考
    【转】oracle null
    【转】JavaScript闭包
    【转】Ext JS xtype
    【转】EXT JS MVC开发模式
    【转】Ext.ajax.request 中的success和failure
    【转】Oracle job procedure 存储过程定时任务
    JDK重要包和Java学习方法论
    rownum
    【转】Js获取当前日期时间及格式化操作
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10615127.html
Copyright © 2011-2022 走看看