伸展树
题目描述
第一次写splay没调就A
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<string>
#include<bitset>
#include<queue>
#include<map>
#include<set>
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
void print(int x)
{if(x<0)putchar('-'),x=-x;if(x>=10)print(x/10);putchar(x%10+'0');}
const int N=100100;
int root;
int ch[N][2],size[N],fa[N];
int V[N],sum[N];
bool rev[N];
inline void pushup(int k)
{
size[k]=size[ch[k][0]]+size[ch[k][1]]+1;
sum[k]=V[k]+sum[ch[k][0]]+sum[ch[k][1]];
}
inline void pushdown(int k)
{
if(rev[k])
{
rev[k]=0;
swap(ch[k][0],ch[k][1]);
rev[ch[k][0]]^=1;rev[ch[k][1]]^=1;
}
}
void build(int l,int r,int pre)
{
if(l>r)return ;
int mid=(l+r)>>1;
fa[mid]=pre;
ch[pre][mid>pre]=mid;
build(l,mid-1,mid);
build(mid+1,r,mid);
pushup(mid);
}
void rotate(int x,int &k)
{
int y=fa[x],z=fa[y],l,r;
l=(ch[y][1]==x);r=l^1;
if(y==k)k=x;
else ch[z][y==ch[z][1]]=x;
fa[x]=z;fa[y]=x;fa[ch[x][r]]=y;
ch[y][l]=ch[x][r];ch[x][r]=y;
pushup(y);pushup(x);
}
void splay(int x,int &k)
{
int y,z;
while(x!=k)
{
y=fa[x],z=fa[y];
if(y!=k)
{
if((ch[y][0]==x)^(ch[z][0]==y))rotate(x,k);
else rotate(y,k);
}
rotate(x,k);
}
}
int find(int k,int rk)
{
pushdown(k);
if(rk<=size[ch[k][0]])return find(ch[k][0],rk);
if(rk>size[ch[k][0]]+1)return find(ch[k][1],rk-size[ch[k][0]]-1);
return k;
}
void rever(int x,int y)
{
x=find(root,x),y=find(root,y+2);
splay(x,root);splay(y,ch[root][1]);
rev[ch[y][0]]^=1;
}
int query(int x,int y)
{
x=find(root,x);y=find(root,y+2);
splay(x,root);splay(y,ch[root][1]);
return sum[ch[y][0]];
}
int main()
{
int n=read(),Q=read();
register int i,x,y;
for(i=1;i<=n;++i)V[i+1]=read();
build(1,n+2,0);root=(n+3)>>1;
char opt[10];
while(Q--)
{
scanf("%s",opt+1);
if(opt[1]=='S')
{
x=read();y=read();
print(query(x,y));puts("");
}
else
{
x=read();y=read();
rever(x,y);
}
}
return 0;
}
/*
6 3
1 6 5 2 1 3
SUM 1 4
REVERS 3 5
SUM 1 4
*/