您的位置:首页 > 其它

POJ 3468 A Simple Problem with Integers

2014-06-03 19:23 363 查看
我只是来练splay的…

照着kuangbin巨巨、cxlove巨巨的代码一点一点学习!

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long LL;
#define keytree ch[ch[root][1]][0]
#define L(x) ch[x][0]
#define R(x) ch[x][1]
#define N 100010

int n,m,tot,root;
int a
,ch
[2],pre
,size
;
LL val
,add
,sum
;

void newnode(int &u,int fa,int w)
{
u=++tot;
L(u)=R(u)=0;
pre[u]=fa;
size[u]=1;
val[u]=w;
add[u]=0;
}

void updatenode(int u,LL w)
{
if(!u) return ;
val[u]+=w;
add[u]+=w;
sum[u]+=w*size[u];
}

void up(int u)
{
size[u]=size[L(u)]+size[R(u)]+1;
sum[u]=sum[L(u)]+sum[R(u)]+val[u];
}

void down(int u)
{
if(add[u])
{
updatenode(L(u),add[u]);
updatenode(R(u),add[u]);
add[u]=0;
}
}

void rotate(int u,int kind)
{
int fa=pre[u];
down(fa);
down(u);
ch[fa][!kind]=ch[u][kind];
pre[ch[u][kind]]=fa;
if(pre[fa]) ch[pre[fa]][ch[pre[fa]][1]==fa]=u;
pre[u]=pre[fa];
ch[u][kind]=fa;
pre[fa]=u;
up(fa);
}

void splay(int u,int goal)
{
int fa,kind;
down(u);
while(pre[u]!=goal)
{
if(pre[pre[u]]==goal) rotate(u,L(pre[u])==u);
else
{
fa=pre[u];
kind=L(pre[fa])==fa;
if(ch[fa][kind]==u)
{
rotate(u,!kind);
rotate(u,kind);
}
else
{
rotate(fa,kind);
rotate(u,kind);
}
}
}
up(u);
if(goal==0) root=u;
}

int getkth(int u,int k)
{
down(u);
int s=size[L(u)]+1;
if(s==k) return u;
if(s>k) return getkth(L(u),k);
else return getkth(R(u),k-s);
}

void build(int &u,int l,int r,int fa)
{
if(l>r) return ;
int mid=(l+r)>>1;
newnode(u,fa,a[mid]);
build(L(u),l,mid-1,u);
build(R(u),mid+1,r,u);
up(u);
}

void init()
{
root=tot=0;
L(root)=R(root)=pre[root]=size[root]=val[root]=add[root]=sum[root]=0;
newnode(root,0,-1);
newnode(R(root),root,-1);
build(keytree,1,n,R(root));
up(R(root));
up(root);
}

void update(int l,int r,int w)
{
splay(getkth(root,l),0);
splay(getkth(root,r+2),root);
updatenode(keytree,w);
up(R(root));
up(root);
}

LL query(int l,int r)
{
splay(getkth(root,l),0);
splay(getkth(root,r+2),root);
return sum[keytree];
}

int main()
{
int u,v,x;
char op[3];
while(~scanf("%d%d",&n,&m))
{
for(u=1;u<=n;u++) scanf("%d",&a[u]);
init();
while(m--)
{
scanf("%s",op);
if(op[0]=='Q')
{
scanf("%d%d",&u,&v);
//cout<<query(u,v)<<endl;
printf("%lld\n",query(u,v));
}
else
{
scanf("%d%d%d",&u,&v,&x);
update(u,v,x);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: