# BZOJ4999 树剖+动态开点

#include<bits/stdc++.h>
#define N 100010
#define lson l , mid , ls[x]
#define rson mid + 1 , r , rs[x]
using namespace std;
map<int , int> mp;
int a[N] , head[N] , to[N << 1] , next[N << 1] , cnt , fa[N] , deep[N] , si[N] , bl[N] , pos[N] , num;
int root[N << 2] , ls[N << 7] , rs[N << 7] , sum[N << 7] , tot , n , clo;
char str[5];
void add(int x , int y) {
to[++cnt] = y , next[cnt] = head[x] , head[x] = cnt;
}
void dfs1(int x) {
int i;
si[x] = 1;
for(i = head[x] ; i ; i = next[i])
if(to[i] != fa[x])
fa[to[i]] = x , deep[to[i]] = deep[x] + 1 , dfs1(to[i]) , si[x] += si[to[i]];
}
void dfs2(int x , int c) {
int i , k = 0;
bl[x] = c , pos[x] = ++num;
for(i = head[x] ; i ; i = next[i])
if(to[i] != fa[x] && si[to[i]] > si[k])
k = to[i];
if(k) {
dfs2(k , c);
for(i = head[x] ; i ; i = next[i])
if(to[i] != fa[x] && to[i] != k)
dfs2(to[i] , to[i]);
}
}
void update(int p , int a , int l , int r , int &x) {
if(!x) x = ++tot;
sum[x] += a;
if(l == r) return;
int mid = (l + r) >> 1;
if(p <= mid) update(p , a , lson);
else update(p , a , rson);
}
int query(int b , int e , int l , int r , int x) {
if(!x) return 0;
if(b <= l && r <= e) return sum[x];
int mid = (l + r) >> 1 , ans = 0;
if(b <= mid) ans += query(b , e , lson);
if(e > mid) ans += query(b , e , rson);
return ans;
}
int solve(int x , int y , int c) {
int ans = 0;
while(bl[x] != bl[y]) {
if(deep[bl[x]] < deep[bl[y]]) swap(x , y);
ans += query(pos[bl[x]] , pos[x] , 1 , n , root[c]) , x = fa[bl[x]];
}
if(deep[x] > deep[y]) swap(x , y);
ans += query(pos[x] , pos[y] , 1 , n , root[c]);
return ans;
}
int main() {
int m , i , x , y , z;
scanf("%d%d" , &n , &m);
for(i = 1 ; i <= n ; i ++ ) scanf("%d" , &a[i]);
for(i = 1 ; i < n ; i ++ ) scanf("%d%d" , &x , &y) , add(x , y) , add(y , x);
dfs1(1) , dfs2(1 , 1);
for(i = 1 ; i <= n ; i ++ ) {
if(!mp[a[i]]) mp[a[i]] = ++clo;
update(pos[i] , 1 , 1 , n , root[mp[a[i]]]);
}
while(m -- ) {
scanf("%s%d%d" , str , &x , &y);
if(str[0] == 'C') {
update(pos[x] , -1 , 1 , n , root[mp[a[x]]]);
if(!mp[y]) mp[y] = ++clo;
update(pos[x] , 1 , 1 , n , root[mp[y]]);
a[x] = y;
} else {
scanf("%d" , &z);
if(!mp[z]) puts("0");
else printf("%d\n" , solve(x , y , mp[z]));
}
}
return 0;
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客