HDU 3966

树链剖分 练模板;

用的 是HH的线段树 虽然之前是我不用的摸板

修改区间 求点值;

CODE:

   

#pragma comment(linker,"/STACK:1024000000,1024000000")
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdlib>
#include <stack>
#include <vector>
#include <set>
#include <map>
using namespace std;
#define N 503456

struct edge
{
int v,next;
}e[N<<1];
int head[N<<1],tot;
int top[N];
int fa[N],dep[N],sz[N],son[N],p[N],fp[N],pos,a[N];

void add(int u,int v)
{
e[tot].v=v;
e[tot].next=head[u];
head[u]=tot++;
}

void init()
{
tot=pos=0;
memset(head,-1,sizeof(head));
memset(son,-1,sizeof(son));
}

void dfs(int u,int pre,int d)
{
dep[u]=d;
sz[u]=1;
fa[u]=pre;
for (int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].v;
if (v==pre) continue;
dfs(v,u,d+1);
sz[u]+=sz[v];
if (son[u]==-1||sz[son[u]]<sz[v]) son[u]=v;
}
}

void getpos(int u,int sp)
{
top[u]=sp;
p[u]=++pos;
fp[pos]=u;
if (son[u]==-1) return;
getpos(son[u],sp);
for (int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].v;
if (v!=son[u]&&v!=fa[u])
getpos(v,v);
}
}

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int sum[N<<2],col[N<<2];

void pushup(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void pushdown(int rt,int m)
{
if (col[rt])
{
col[rt<<1]+=col[rt];
col[rt<<1|1]+=col[rt];
sum[rt<<1]+=col[rt]*(m-(m>>1));
sum[rt<<1|1]+=col[rt]*(m>>1);
col[rt]=0;
}
}
void build(int l,int r,int rt)
{
col[rt]=0;
if (l==r)
{
sum[rt]=a[fp[l]];
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
void update(int L,int R,int c,int l,int r,int rt)
{
if (L<=l&&r<=R)
{
col[rt]+=c;
sum[rt]+=c*(r-l+1);
return;
}
pushdown(rt,r-l+1);
int m=(l+r)>>1;
if (L<=m) update(L,R,c,lson);
if (m<R) update(L,R,c,rson);
pushup(rt);
}

int query(int p,int l,int r,int rt)
{
if (l==r) return sum[rt];
pushdown(rt,r-l+1);
int m=(l+r)>>1;
if (p<=m) return query(p,lson);
if (p>m) return query(p,rson);
}

void lca(int u,int v,int c)
{
int fu=top[u],fv=top[v];
while (fu!=fv)
{
if (dep[fu]<dep[fv])
{
swap(fu,fv);
swap(u,v);
}
update(p[fu],p[u],c,1,pos,1);
u=fa[fu];
fu=top[u];
}
if (dep[u]>dep[v]) swap(u,v);
update(p[u],p[v],c,1,pos,1);
}

int main()
{
int n,m,t,u,v,w;
while (scanf("%d%d%d",&n,&m,&t)!=EOF)
{
init();
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
for (int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
dfs(1,0,0);
getpos(1,1);
build(1,pos,1);
char op[10];
while (t--)
{
scanf("%s",op);
if (op[0]=='Q')
{
scanf("%d",&u);
printf("%d ",query(p[u],1,pos,1));
}
else
{
scanf("%d%d%d",&u,&v,&w);
if (op[0]=='D') w=-w;
lca(u,v,w);
}
}
}
return 0;
}

原文地址:https://www.cnblogs.com/forgot93/p/4297263.html