题目大意:一颗N个结点的树,给你P次操作
操作 I :结点C1-->C2之间的所有结点权值加K;
操作D:结点C1->C2之间的所有结点权值减K;
操作Q:询问结点C的值。
思路:这一眼看上去就知道是一道裸的树链剖分(点操作),就不多说了直接上代码。没学过树链剖分的建议先入门再来看代码。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define N 50005
using namespace std;
struct node
{
int u,v,next;
} edge[N<<2];
int pre[N],cnt;
int son[N],dep[N],siz[N];
int tid[N],id,top[N],fa[N];
int n,m,p;
int num[N],add[N<<2];
int scan()
{
int res = 0, ch, flag = 0;
if((ch = getchar()) == '-')
flag = 1;
else if(ch >= '0' && ch <= '9')
res = ch - '0';
while((ch = getchar()) >= '0' && ch <= '9' )
res = res * 10 + ch - '0';
return flag ? -res : res;
}
void init()
{
cnt = id = 0;
memset(pre, -1, sizeof(pre));
memset(siz, 0, sizeof(siz));
memset(add, 0, sizeof(add));
memset(son, 0, sizeof(son));
}
void addEdge(int u, int v)
{
edge[cnt].u = u;
edge[cnt].v = v;
edge[cnt].next = pre[u];
pre[u] = cnt++;
}
void dfs1(int u, int f, int dp)
{
dep[u] = dp;
fa[u] = f;
son[u] = 0;
siz[u] = 1;
for(int i = pre[u]; ~i; i=edge[i].next)
{
int v = edge[i].v;
if(v != f)
{
dfs1(v, u, dp+1);
siz[u] += siz[v];
if(siz[v] > siz[son[u]])
son[u] = v;
}
}
}
void dfs2(int u, int tp)
{
tid[u] = ++id;
top[u] = tp;
if(son[u])
dfs2(son[u], tp);
for(int i = pre[u]; ~i; i=edge[i].next)
{
int v = edge[i].v;
if(v != fa[u] && v != son[u])
dfs2(v, v);
}
}
void update(int rt, int l, int r, int ql, int qr, int v)
{
if(ql <= l && r <= qr)
{
add[rt] += v;
return ;
}
int mid = (l + r) >> 1;
if(add[rt])
{
add[rt<<1] += add[rt];
add[rt<<1|1] += add[rt];
add[rt] = 0;
}
if(ql <= mid)
update(rt<<1, l, mid, ql, qr, v);
if(qr > mid)
update(rt<<1|1, mid+1, r, ql, qr, v);
}
int query(int rt, int l, int r, int pos)
{
if(l == r && l == pos)
return add[rt];
int mid = (l + r) >> 1;
if(add[rt])
{
add[rt<<1] += add[rt];
add[rt<<1|1] += add[rt];
add[rt] = 0;
}
if(pos <= mid)
return query(rt<<1, l, mid, pos);
return query(rt<<1|1, mid+1, r, pos);
}
void LCA(int u, int v, int k)
{
while(top[u] != top[v])
{
if(dep[top[u]] < dep[top[v]])
swap(u, v);
update(1, 1, n, tid[top[u]], tid[u], k);
u = fa[top[u]];
}
if(dep[u] > dep[v])
swap(u, v);
update(1, 1, n, tid[u], tid[v], k);
}
int main()
{
while(~scanf("%d%d%d", &n,&m,&p))
{
for(int i = 1; i <= n; ++i)
num[i] = scan();
init();
while(m--)
{
int u = scan();
int v = scan();
addEdge(u, v);
addEdge(v, u);
}
dfs1(1, 1, 1);
dfs2(1, 1);
while(p--)
{
char op[10];
int c1,c2,k;
scanf("%s", op);
if(op[0] == 'I')
{
scanf("%d%d%d", &c1,&c2,&k);
LCA(c1, c2, k);
}
else if(op[0] == 'D')
{
scanf("%d%d%d", &c1,&c2,&k);
LCA(c1, c2, -k);
}
else
{
scanf("%d", &c1);
printf("%d\n", num[c1] + query(1, 1, n, tid[c1]));
}
}
}
return 0;
}