0分求助
查看原帖
0分求助
422387
VIOLET__FOREVER楼主2022/9/11 17:03
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ls root<<1
#define rs root<<1|1 
const int N=30005;
int n,m;
struct node{
	int to,next;
}edge[N<<1];
int head[N<<1],tot,cnt;
int top[N],son[N],arr[N],tr[N<<2],tr_max[N<<2],fa[N],dep[N],siz[N],id[N],rid[N];

void add(int x,int y){
	tot++;
	edge[tot].to=y;
	edge[tot].next=head[x];
	head[x]=tot;
}
void dfs1(int x){
	siz[x]=1;
	dep[x]=dep[fa[x]]+1;
	for(int i=head[x];i!=0;i=edge[i].next){
		int xx=edge[i].to;
		if(xx==fa[x]) continue;
		fa[xx]=x;
		dfs1(xx);
		siz[x]+=siz[xx];
		if(!son[x] || siz[xx]>siz[son[x]]) son[x]=xx;
	}
}
void dfs2(int x,int tv){
	top[x]=tv;
	cnt++;
	id[x]=cnt;
	rid[cnt]=x;
	if(son[x]) dfs2(son[x],tv);
	for(int i=head[x];i!=0;i=edge[i].next){
		int xx=edge[i].to;
		if(xx==fa[x] || xx==son[x]) continue;
		dfs2(xx,xx);
	}
}
void pushup(int root){
	tr[root]=tr[ls]+tr[rs];
	tr_max[root]=max(tr_max[ls],tr_max[rs]);
}
void build(int root,int start,int end){
	if(start==end){
		tr[root]=arr[rid[start]];
		tr_max[root]=tr[root];
		return ;
	}
	int mid=(start+end)>>1;
	build(ls,start,mid);
	build(rs,mid+1,end);
	pushup(root);
}
void updata(int root,int start,int end,int loc,int val){
	if(start==end){
		tr[root]=val;
		tr_max[root]=val;
		return ;
	}
	int mid=(start+end)>>1;
	if(loc<=mid) updata(ls,start,mid,loc,val);
	else updata(rs,mid+1,end,loc,val);
	pushup(root);
}
int qurey(int root,int start,int end,int l,int r){
	if(start>=l && end<=r) return tr[root];
	int mid=(start+end)>>1;
	int res=0;
	if(mid>=l) res+=qurey(ls,start,mid,l,r);
	if(mid<r) res+=qurey(rs,mid+1,end,l,r);
	return res;
}
int qurey_max(int root,int start,int end,int l,int r){
	if(start>=l && end<=r) return tr_max[root];
	int mid=(start+end)>>1;
	int res=0;
	if(mid>=l) res=max(res,qurey_max(ls,start,mid,l,r));
	if(mid<r) res=max(res,qurey_max(rs,mid+1,end,l,r));
	return res;
}
int shup(int x,int y){
	int res=0;
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]]) swap(x,y);
		res+=qurey(1,1,n,id[top[x]],id[x]);
		x=fa[top[x]];
	}
	if(dep[x]>dep[y]) swap(x,y);
	res+=qurey(1,1,n,id[x],id[y]);
	return res;
}
int shup_max(int x,int y){
	int res=0;
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]]) swap(x,y);
		res=max(res,qurey_max(1,1,n,id[top[x]],id[x]));
		x=fa[top[x]];
	}
	if(dep[x]>dep[y]) swap(x,y);
	res=max(res,qurey_max(1,1,n,id[x],id[y]));
	return res;
}
signed main(){
	cin>>n;
	for(int i=1;i<n;i++){
		int x,y;
		cin>>x>>y;
		add(x,y),add(y,x);
	}
	dfs1(1);
	dfs2(1,1);
	for(int i=1;i<=n;i++) cin>>arr[i];
	build(1,1,n);
	cin>>m;
	for(int i=1;i<=m;i++){
		string ch;
		int x,y;
		cin>>ch>>x>>y;
		if(ch[1]=='H'){
			updata(1,1,n,x,y);
		}
		else if(ch[1]=='M'){
			int ans=shup_max(x,y);
			cout<<ans<<endl;
		}
		else{
			int ans=shup(x,y);
			cout<<ans<<endl;
		}
	}
	return 0;
}
2022/9/11 17:03
加载中...