对每一个权值开一棵线段树,维护区间和。空间不够,要动态开点。
#include <bits/stdc++.h>
using namespace std;
#define N 100010
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*f;
}
int n,m,a[N],h[N],num=0,cnt=0,tot=0,root[300010];
int dep[N],fa[N],son[N],size[N],id[N],dfn=0,top[N];
map<int,int>mp;
struct edge{
int to,next;
}data[N<<1];
inline void add(int x,int y){
data[++num].to=y;data[num].next=h[x];h[x]=num;
}
struct node{
int lc,rc,sum;
}tree[4000010];
void dfs1(int x){
size[x]=1;
for(int i=h[x];i;i=data[i].next){
int y=data[i].to;
if(y==fa[x]) continue;
fa[y]=x;dep[y]=dep[x]+1;dfs1(y);size[x]+=size[y];
if(size[y]>size[son[x]]) son[x]=y;
}
}
void dfs2(int x,int tp){
id[x]=++dfn;top[x]=tp;
if(son[x]) dfs2(son[x],tp);
for(int i=h[x];i;i=data[i].next){
int y=data[i].to;
if(y==fa[x]||y==son[x]) continue;
dfs2(y,y);
}
}
inline void pushup(int p){
tree[p].sum=tree[tree[p].lc].sum+tree[tree[p].rc].sum;
}
void add1(int &p,int l,int r,int x,int val){
if(!p) p=++cnt;
if(l==r){tree[p].sum+=val;return;}
int mid=l+r>>1;
if(x<=mid) add1(tree[p].lc,l,mid,x,val);
else add1(tree[p].rc,mid+1,r,x,val);
pushup(p);
}
int qsum(int p,int l,int r,int x,int y){
if(!p) return 0;
if(x<=l&&r<=y) return tree[p].sum;
int mid=l+r>>1,res=0;
if(x<=mid) res+=qsum(tree[p].lc,l,mid,x,y);
if(y>mid) res+=qsum(tree[p].rc,mid+1,r,x,y);
return res;
}
int solve(int x,int y,int val){
if(!mp[val]) return 0;int res=0;
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]]) swap(x,y);
res+=qsum(root[mp[val]],1,n,id[top[x]],id[x]);
x=fa[top[x]];
}
if(id[x]>id[y]) swap(x,y);
return res+qsum(root[mp[val]],1,n,id[x],id[y]);
}
int main(){
// freopen("a.in","r",stdin);
n=read();m=read();
for(int i=1;i<=n;++i) a[i]=read();
for(int i=1;i<n;++i){
int x=read(),y=read();add(x,y);add(y,x);
}dep[1]=1;dfs1(1);dfs2(1,1);
for(int i=1;i<=n;++i){
if(!mp[a[i]]) mp[a[i]]=++tot;
add1(root[mp[a[i]]],1,n,id[i],1);
}
while(m--){
char op[1];scanf("%s",op);int x=read(),y=read();
if(op[0]=='C'){
add1(root[mp[a[x]]],1,n,id[x],-1);a[x]=y;
if(!mp[a[x]]) mp[a[x]]=++tot;
add1(root[mp[a[x]]],1,n,id[x],1);
}
else printf("%d\n",solve(x,y,read()));
}
return 0;
}