树剖,维护区间最大值以及区间和,最大值为1的时候就不需要下传更改了。
#include<bits/stdc++.h>
#define lc l,mid,x<<1
#define rc mid+1,r,x<<1|1
using namespace std;
typedef long long LL;
typedef int lint;
const lint maxn = 100005;
const lint maxm = 200005;
lint tot,he[maxn],ver[maxm],ne[maxm],id[maxn];
LL v[maxn];
void add( lint x,lint y){
ver[++tot] = y;
ne[tot] = he[x];
he[x] = tot;
}
lint sz[maxn],f[maxn],son[maxn],d[maxn];
void dfs1(lint x){
sz[x] = 1;
lint mm = 0;son[x] = 0;
for( lint cure = he[x];cure;cure = ne[cure] ){
lint y = ver[cure];
if( y == f[x] ) continue;
d[y] = d[x]+1;
f[y] = x;
dfs1(y);
sz[x] += sz[y];
if( sz[y] > mm ){
mm = sz[y];
son[x] = y;
}
}
}
lint top[maxn],h[maxn],num;
void dfs2( lint x ){
h[x] = ++num;
id[num]=x;
if( son[ f[x] ] == x ){
top[x] = top[ f[x] ];
}else{
top[x] = x;
}
if( son[x] ){
dfs2(son[x]);
}
for( lint cure = he[x];cure;cure = ne[cure] ){
lint y = ver[cure];
if( y == f[x] || y == son[x] )continue;
dfs2(y);
}
}
LL tree[4*maxn],mm[4*maxn];
void push_up( lint x ){
tree[x] = tree[x<<1]+tree[x<<1|1];
mm[x] = max( mm[x<<1],mm[x<<1|1] );
}
void build_tree( lint l,lint r,lint x ){
if( l == r ){
tree[x]=mm[x]=v[id[l]];
return;
}
lint mid = l+r>>1;
build_tree(lc);
build_tree(rc);
push_up(x);
}
void update( lint ll,lint rr,lint l,lint r,lint x ){
if( ll <= l && rr >= r ){
if( mm[x]==1 )return;
if( l==r ){
tree[x] = sqrt(tree[x]);
mm[x] = sqrt( mm[x] );
return;
}
}
lint mid = l+r >> 1;
if( ll <= mid ) update( ll,rr,lc );
if( rr > mid ) update( ll,rr,rc );
push_up(x);
}
LL ask( lint ll,lint rr,lint l,lint r,lint x ){
if( ll <= l&& rr >= r ){
return tree[x];
}
LL res = 0;
lint mid = l+r>>1;
if( ll <= mid ){
res += ask( ll,rr,lc ) ;
}
if( rr > mid ){
res += ask( ll,rr,rc ) ;
}
return res;
}
LL solveask( lint x,lint y ){
LL res = 0;
while( top[x] != top[y] ){
if( d[ top[x] ] < d[ top[y] ] )swap( x,y );
res += ask( h[ top[x] ],h[x],1,num,1 );
x = f[ top[x] ];
}
if( d[x] < d[y] ){
swap( x,y );
}
res += ask( h[ y ],h[x],1,num,1 );
return res;
}
void solvechange( lint x,lint y ){
while( top[x] != top[y] ){
if( d[ top[x] ] < d[ top[y] ] ) swap(x,y);
update( h[top[x]],h[x],1,num,1 );
x = f[ top[x] ];
}
if( d[x] < d[y] ){
swap(x,y);
}
update( h[ y ],h[x],1,num,1 );
}
int main(){
lint n,q;
scanf("%d%d", &n,&q);
for( lint i = 1;i <= n;i++ ) {
scanf("%lld",&v[i]);
}
tot = 1;
for (lint x, y, i = 1; i <= n - 1; i++) {
scanf("%d%d", &x, &y);
add(x, y);
add(y, x);
}
dfs1(1);
dfs2(1);
build_tree(1, n, 1);
lint op,x,y;
for( lint i = 1;i <= q;i++ ){
scanf("%d%d%d",&op,&x,&y);
if( op == 1 ){
LL ans = solveask(x,y );
printf("%lld\n",ans);
}else{
solvechange(x,y);
}
}
return 0;
}