题目分析
很明显这道题是一道树链剖分的题目,这个中间用线段树处理的让我感觉老是很怪异!!可能没有这样处理过线段树吧!对于第一种操作,很明显就是树链剖分的简单处理,对于第二种操作只需要更改相对应线段树中的值就可以了,对于第三种由于轻重链剖分对于每棵子树上的东西都需要处理,但是每棵子树上所有节点所在的区间是连续的,因此转化为了线段树的区间更新,其他的都不难写了。还有一点我们用w[]表示树中的节点在线段树中的值,但是建树的时候我们需要知道在线段树中的位置对应树中的几号节点,另开一个数组存一下即可。
#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100005;
#define mid (L+R)/2
#define lson o<<1, L, mid
#define rson o<<1|1, mid+1, R
int siz[maxn],fa[maxn],son[maxn],dep[maxn],top[maxn],w[maxn],fw[maxn],head[maxn],cnt,tot;
int sum[maxn<<2],lazy[maxn<<2],fact[maxn<<2],val[maxn];
void build(int o,int L,int R){
if(L == R){
sum[o] = val[fw[L]];
return ;
}
build(lson);
build(rson);
sum[o] = sum[o<<1] + sum[o<<1|1];
}
void pushdown(int o){
if(lazy[o]){
lazy[o<<1] = lazy[o<<1|1] = lazy[o];
fact[o<<1] = sum[o<<1];
fact[o<<1|1] = sum[o<<1|1];
lazy[o] = 0;
}
}
void update(int o,int L,int R,int l,int r,int val){
if(lazy[o] && val) return ;
if(l <= L && R <= r){
lazy[o] = val;
if(lazy[o]) fact[o] = sum[o];
else fact[o] = 0;
return ;
}
pushdown(o);
if(l <= mid) update(lson, l, r, val);
if(r > mid) update(rson, l, r, val);
fact[o] = fact[o<<1] + fact[o<<1|1];
}
struct Edge{
int to,next;
}e[maxn<<2];
void addedge(int from, int to){
e[cnt].to = to;
e[cnt].next = head[from];
head[from] = cnt++;
}
void dfs1(int now){
siz[now] = 1;
son[now] = 0;
for(int u = head[now]; u != -1; u = e[u].next){
int v = e[u].to;
if(v != fa[now]){
dep[v] = dep[now] + 1;
fa[v] = now;
dfs1(v);
siz[now] += siz[v];
if(siz[son[now]] < siz[v]) son[now] = v;
}
}
}
void dfs2(int now,int tp){
w[now] = ++tot;
top[now] = tp;
fw[tot] = now;
if(son[now]) dfs2(son[now], top[now]);
for(int u = head[now]; u != -1; u = e[u].next){
int v = e[u].to;
if(v != fa[now] && v != son[now])
dfs2(v, v);
}
}
void solve(int a,int b){
int f1 = top[a],f2 = top[b];
while(f1 != f2){
if(dep[f1] < dep[f2]){
swap(f1,f2);
swap(a,b);
}
update(1, 1, tot, w[f1], w[a], 1);
a = fa[f1];
f1 = top[a];
}
if(dep[a] > dep[b]) swap(a,b);
update(1, 1, tot, w[a], w[b], 1);
}
void init(){
cnt = tot = 0;
memset(head, -1, sizeof(head));
memset(dep, 0, sizeof(dep));
memset(son, 0, sizeof(son));
memset(siz, 0, sizeof(siz));
memset(sum, 0, sizeof(sum));
memset(lazy, 0, sizeof(lazy));
memset(fact, 0, sizeof(fact));
}
int main(){
int T,N,Q;
scanf("%d", &T);
while(T--){
init();
scanf("%d", &N);
for(int i = 1; i <= N; i++)
scanf("%d", &val[i]);
int op,from,to;
for(int i = 1; i < N; i++){
scanf("%d%d", &from, &to);
addedge(from, to);
addedge(to, from);
}
dfs1(1);
dfs2(1, 1);
build(1, 1, tot);
scanf("%d", &Q);
while(Q--){
scanf("%d", &op);
if(op == 1){
scanf("%d%d", &from, &to);
solve(from, to);
}
else if(op == 2){
scanf("%d", &from);
update(1, 1, tot, w[from], w[from], 0);
}
else{
scanf("%d", &from);
update(1, 1, tot, w[from], w[from]+siz[from]-1, 1);
}
printf("%d\n", fact[1]);
}
}
return 0;
}