bzoj3223: Tyvj 1729 文艺平衡树

splay的经典操作:翻转区间-->交换左右子树,注意打标记降低翻转次数

如何找到要操作的区间[l,r]:将当前排名(size)为l-1 +1 的节点转到根,将当前排名为r+2的节点转到根的右子树的根节点,则根的右子树的根节点的左子树为所求区间,直接打标记就可以了。

注意

1.标记是在每一次访问到一个新的节点是就要pushdown的

2.区分一个节点的排名和这个节点的值:这个节点的排名是它是当前数组中的第几个,用左儿子的size+1表示;这个节点的值是题目中输入的数字,在本题中是1~n

3.增加数字为0和n+1的两个哨兵节点,因为如果对区间1~x或 x~n操作,用到前后的节点就需要0和n+1。但在数组版的写法中值为0 和n+1的节点的编号是>=1的,不会为0。感谢whk告诉我这个。

4.注意build的写法,返回区间[l,r]的根节点的编号

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define MAXN 100010
#define INF 0x7fffffff
#define lc tr[x].ch[0]
#define rc tr[x].ch[1]
struct node{
    int ch[2],f,v,sz;
    bool rv;
    void set(int x){v=x;ch[0]=ch[1]=f=rv=0;sz=1;}
}tr[MAXN];
int n,m,root,tot,l,r,x1,x2;
void updata(int x)//维护必备
{
    if (!x) return ;
    tr[x].sz=1+tr[lc].sz+tr[rc].sz;
}
void PD(int x)//打标记必备
{
    if (!x) return ;
    if (tr[x].rv)
    {
        tr[lc].rv^=1;tr[rc].rv^=1;
        tr[x].rv=0;
        int t=lc;lc=rc;rc=t;
    }
}
void SC(int x,int y,bool z)
{
    tr[x].ch[z]=y;tr[y].f=x;
}
inline bool d(int x) {return tr[tr[x].f].ch[1]==x;}
void rot(int x)
{
    int y=tr[x].f,z=tr[y].f,tt=d(x);
    SC(z,x,d(y));SC(y,tr[x].ch[!tt],tt);SC(x,y,!tt);
    updata(y);
}
void splay(int x,int f)
{
    PD(x);
    if (f==0) root = x;
    while (tr[x].f!=f)
    {
        if (tr[tr[x].f].f==f) {rot(x);break;}
        if (d(x)==d(tr[x].f)) {rot(tr[x].f);rot(x);} else {rot(x);rot(x);}
    }
    updata(x);
}
int build(int l,int r)
{
    if (l>r) return 0;
    int x=++tot;
    int mid=(l+r) >> 1;
    tr[x].set(mid);
    lc=build(l,mid-1);
    rc=build (mid+1,r);
    tr[lc].f=tr[rc].f=x;
    updata(x);
    return x;
}
int find(int x,int y)
{
    PD(x);//有标记就必须PD,且写成递归的形式
    if (tr[lc].sz+1<y) return find(rc,y-1-tr[lc].sz);
    else if (tr[lc].sz+1==y) return x;
    else return find(lc,y);
}
void dfs(int x)
{
    PD(x);//!!打的标记在每一次访问之前都要下传,在递归答案的时候也要
    if (tr[x].ch[0]) dfs(tr[x].ch[0]);
    if (tr[x].v<=n && tr[x].v>=1)
        cout<<tr[x].v<<' ';
    if (tr[x].ch[1]) dfs(tr[x].ch[1]);
}
int main()
{
    scanf("%d%d", &n, &m);
    tot=root=0;
    tr[0].v=tr[n+1].v=INF;
    root=build(0,n+1);//0 和n+1 是哨兵节点
    while (m--)
    {
        scanf("%d%d", &l, &r);
        x1=find(root,l);x2=find(root,r+2);
        splay(x1,0);splay(x2,x1);updata(root);
        tr[tr[x2].ch[0]].rv^=1;
        updata(tr[x2].ch[0]);updata(x2);updata(root);
    }
    dfs(root);
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值