#include<bits/stdc++.h>
using namespace std;
int n,q;
int w[100005],c[100005];
vector<int>adj[100005];
int siz[100005],dfn[100005],fa[100005],dep[100005];
int hson[100005],top[100005],counter;
int root[100005];
struct Node {
int l,r;
int maxi,sum;
} tree[20000005];
void add(int l,int r,int pos,int x,int &rt) {
if(!rt)rt = ++counter;
tree[rt].maxi = max(tree[rt].maxi,x);
tree[rt].sum += x;
int mid = (l+r)>>1;
if(l == r) {
return ;
} else if(mid>=pos) {
add(l,mid,pos,x,tree[rt].l);
} else {
add(mid+1,r,pos,x,tree[rt].r);
}
}
void del(int l,int r,int pos,int &rt) {
if(l == r) {
tree[rt].maxi = tree[rt].sum = 0;
return ;
}
int mid = (l+r)>>1;
if(mid>=pos) {
del(l,mid,pos,tree[rt].l);
} else {
del(mid+1,r,pos,tree[rt].r);
}
tree[rt].maxi = max(tree[tree[rt].l].maxi,tree[tree[rt].r].maxi);
tree[rt].sum = tree[tree[rt].l].sum+tree[tree[rt].r].sum;
}
int query(int l,int r,int ql,int qr,int rt,int op) {
if(l>qr||r<ql) {
return 0;
} else if(l>=ql&&r<=qr) {
if(op == 1) {
return tree[rt].sum;
} else {
return tree[rt].maxi;
}
}
int mid = (l+r)>>1;
if(op == 1)return query(l,mid,ql,qr,tree[rt].l,op)+query(mid+1,r,ql,qr,tree[rt].r,op);
else return max(query(l,mid,ql,qr,tree[rt].l,op),query(mid+1,r,ql,qr,tree[rt].r,op));
}
int Query(int x,int y,int col,int op) {
int result = 0;
while(top[x] != top[y]) {
if(dep[top[x]]<dep[top[y]]) {
swap(x,y);
}
if(op == 1) {
result += query(1,n,dfn[top[x]],dfn[x],root[col],op);
} else {
result = max(result,query(1,n,dfn[top[x]],dfn[x],root[col],op));
}
x = fa[top[x]];
}
if(dep[x]<dep[y])swap(x,y);
if(op == 1) {
result += query(1,n,dfn[y],dfn[x],root[col],op);
} else {
result = max(result,query(1,n,dfn[y],dfn[x],root[col],op));
}
return result;
}
void DFS1(int cur,int lst) {
siz[cur] = 1;
dep[cur] = dep[lst]+1;
fa[cur] = lst;
for(auto x : adj[cur]) {
if(x == lst) continue;
DFS1(x,cur);
siz[cur] += siz[x];
if(siz[x]>siz[hson[cur]]) {
hson[cur] = x;
}
}
}
void DFS2(int cur,int st) {
top[cur] = st;
dfn[cur] = ++counter;
if(hson[cur] != 0) {
DFS2(hson[cur],st);
}
for(auto x : adj[cur]) {
if(x == hson[cur]||x == fa[cur]) continue;
DFS2(x,x);
}
}
int main() {
cin>>n>>q;
for(int i = 1; i <= n; i++) {
scanf("%d %d",&w[i],&c[i]);
}
for(int i = 0; i<n-1; i++) {
int u,v;
scanf("%d %d",&u,&v);
adj[u].push_back(v);
adj[v].push_back(u);
}
DFS1(1,0);
DFS2(1,1);
counter = 0;
for(int i = 1; i <= n; i++) {
add(1,n,dfn[i],w[i],root[c[i]]);
}
while(q--) {
char op[2];
int x,y;
cin>>op>>x>>y;
if(op[1] == 'C') {
del(1,n,dfn[x],root[c[x]]);
add(1,n,dfn[x],w[x],root[y]);
c[x] = y;
} else if(op[1] == 'W') {
del(1,n,dfn[x],root[c[x]]);
add(1,n,dfn[x],y,root[c[x]]);
w[x] = y;
} else if(op[1] == 'S') {
printf("%d\n",Query(x,y,c[x],1));
} else {
printf("%d\n",Query(x,y,c[x],2));
}
}
}
同样一份代码,使用 C++ 20 评测输出 0,但是使用 C++ 17 通过了()