思路:
树链剖分+2个树状数组。注意权值可以取负数,求最大值时要注意。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int son[N];//son[i]表示i的重儿子
int size[N];//size[i]表示i为根包含自己的字数节点个数
int f[N];//f[i]表示i的父亲
int dep[N];//dep[i]表示i的深度
vector<int> G[N];
void addedge(int u,int v)
{
G[u].push_back(v);
G[v].push_back(u);
}
void dfs1(int cur,int fa)
{
size[cur]=1;
for(int i=0;i<G[cur].size();i++)
{
int to=G[cur][i];
if(to==fa) continue;
dep[to]=dep[cur]+1;
f[to]=cur;
dfs1(to,cur);
size[cur]+=size[to];
if(size[to]>size[son[cur]]) son[cur]=to;
}
}
int top[N];//top[i]表示节点i所在链的顶端
int id[N];//id[i]表示i的新编号
int val[N];//val[i]表示新编号的点权
int w[N];//d[i]表示原编号的点权
int cnt,n;
void dfs2(int cur,int t)
{
id[cur]=++cnt;
val[cnt]=w[cur];
top[cur]=t;
if(son[cur]) dfs2(son[cur],t);
for(int i=0;i<G[cur].size();i++)
if(G[cur][i]!=f[cur]&&G[cur][i]!=son[cur])
dfs2(G[cur][i],G[cur][i]);
}
int c[N],a[N];
int lowbit(int x)
{
return x & (-x);
}
void updata1(int i, int k)
{
while (i <= n)
{
c[i] += k;
i += lowbit(i);
}
}
int getsum(int i)
{
int res = 0;
while (i > 0)
{
res += c[i];
i -= lowbit(i);
}
return res;
}
int C[N],A[N];
void updata2(int x)
{
int lx, i;
while (x <= n)
{
C[x] = A[x];
lx = lowbit(x);
for (i=1; i<lx; i<<=1)
C[x] = max(C[x], C[x-i]);
x += lowbit(x);
}
}
int query(int x, int y)
{
int ans = -10000000;
while (y >= x)
{
ans = max(A[y], ans);
y --;
for (; y-lowbit(y) >= x; y -= lowbit(y))
ans = max(C[y], ans);
}
return ans;
}
void update_val(int x,int z)
{
int sum=getsum(id[x])-getsum(id[x]-1);
updata1(id[x],z-sum);
A[id[x]]=z;
updata2(id[x]);
}
int query_val(int x, int y)
{
int ans = 0, fx = top[x], fy = top[y];
while (fx != fy)
{
if (dep[fx] < dep[fy]) swap(x, y), swap(fx, fy);
ans+=getsum(id[x])-getsum(id[fx]-1);
x = f[fx], fx = top[x];
}
if (id[x] > id[y]) swap(x, y);
ans+=getsum(id[y])-getsum(id[x]-1);
return ans;
}
int query_max(int x,int y)
{
int ans = -10000000, fx = top[x], fy = top[y];
while (fx != fy)
{
if (dep[fx] < dep[fy]) swap(x, y), swap(fx, fy);
ans=max(ans,query(id[fx],id[x]));
x = f[fx], fx = top[x];
}
if (id[x] > id[y]) swap(x, y);
ans=max(ans,query(id[x],id[y]));
return ans;
}
void init()
{
cnt=0;
memset(son,0,sizeof(son));
memset(size,0,sizeof(size));
memset(f,0,sizeof(f));
memset(dep,0,sizeof(dep));
memset(a, 0, sizeof(a));
memset(A,0,sizeof(A));
memset(c,0,sizeof(c));
memset(C,0,sizeof(C));
for(int i=1;i<=n;i++) G[i].clear();
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin>>n;
init();
int u,v;
for(int i=0;i<n-1;i++)
{
cin>>u>>v;
addedge(u,v);
}
for (int i=1;i<=n;i++) cin >> w[i];
f[1]=1;
top[1]=1;
dfs1(1,1);
dfs2(1,1);
for(int i=1;i<=n;i++)
{
a[i]=val[i];
A[i]=val[i];
updata1(i,a[i]);
updata2(i);
}
int m;
cin>>m;
while(m--)
{
string flag;
int x,y;
cin>>flag>>x>>y;
if(flag=="CHANGE") update_val(x,y);
else if(flag=="QMAX") cout<<query_max(x,y)<<endl;
else cout<<query_val(x,y)<<endl;
}
return 0;
}