只能过样例代码求调教悬一关
查看原帖
只能过样例代码求调教悬一关
754502
_AyachiNene楼主2023/5/15 20:47
#include<bits/stdc++.h>
#define ls root*2
#define rs root*2+1
#define Maxn 114514
#define mid (t[root].l+t[root].r)/2
#define int long long
using namespace std;
struct node
{
	int to,nxt;
}e[Maxn];
int head[Maxn],cnt1,w[Maxn],a[Maxn],n,q;
void add_edge(int u,int v)
{
	e[++cnt1].to=v;
	e[cnt1].nxt=head[u];
	head[u]=cnt1;
}
//--------------------------
struct node1
{
	int val,maxn,l,r;
}t[Maxn];
void bld(int l,int r,int root)
{
	t[root].l=l;
	t[root].r=r;
	if(l==r)
	{
		t[root].val=w[l];
		t[root].maxn=w[l];
		return;
	}
	bld(l,mid,ls);
	bld(mid+1,r,rs);
	t[root].maxn=max(t[ls].maxn,t[rs].maxn);
	t[root].val=t[ls].val+t[rs].val;
}
void add(int x,int root,int k)
{
	if(t[root].l==t[root].r)
	{
		t[root].val=k;
		t[root].maxn=k;
		return;
	}
	if(x<=mid)
		add(x,ls,k);
	else
		add(x,rs,k);
	t[root].maxn=max(t[ls].maxn,t[rs].maxn);
	t[root].val=t[ls].val+t[rs].val;
}
int ask_max(int x,int y,int root)
{
	int ans=0;
	if(t[root].l>=x&&t[root].r<=y)
		return t[root].maxn;
	if(x<=mid)
		ans=max(ans,ask_max(x,y,ls));
	if(y>mid)
		ans=max(ans,ask_max(x,y,rs));
	return ans;
}
int query(int x,int y,int root)
{
	int ans=0;
	if(t[root].l>=x&&t[root].r<=y)
		return t[root].val;
	if(x<=mid)
		ans+=query(x,y,ls);
	if(y>mid)
		ans+=query(x,y,rs);
	return ans;
}
//--------------------------
int size[Maxn],son[Maxn],top[Maxn],dfn[Maxn],cnt,f[Maxn],dep[Maxn];
void dfs1(int u,int fa)
{
	size[u]=1;
	for(int i=head[u];i;i=e[i].nxt)
	{
		int v=e[i].to;
		if(v!=fa)
		{
			f[v]=u;
			dep[v]=dep[u]+1;
			dfs1(v,u);
			size[u]+=size[v];
			if(size[son[u]]<size[v])
				son[u]=v;
		}
	}
}
void dfs2(int u,int t)
{
	dfn[u]=++cnt;
	w[cnt]=a[u];
	top[u]=t;
	if(son[u])
		dfs2(son[u],t);
	for(int i=head[u];i;i=e[i].nxt)
	{
		int v=e[i].to;
		if(v!=f[u]&&v!=son[u])
			dfs2(v,v);
	}
}
int _max(int x,int y)
{
	int ans=0;
	while(top[x]!=top[y])
	{
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		ans=max(ans,ask_max(dfn[top[x]],dfn[x],1));
		x=f[top[x]];
	}
	if(dep[x]>dep[y])
		swap(x,y);
	ans=max(ans,ask_max(dfn[x],dfn[y],1));
	return ans;
}
int sum(int x,int y)
{
	int ans=0;
	while(top[x]!=top[y])
	{
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		ans+=query(dfn[top[x]],dfn[x],1);
		x=f[top[x]];
	}
	if(dep[x]>dep[y])
		swap(x,y);
	ans+=query(dfn[x],dfn[y],1);
	return ans;
}
signed main()
{
	cin>>n;
	for(int i=1;i<n;i++)
	{
		int u,v;
		cin>>u>>v;
		add_edge(u,v);
		add_edge(v,u);
	}
	for(int i=1;i<=n;i++)
		cin>>a[i];
	dfs1(1,0);
	dfs2(1,1);
	bld(1,n,1);
	cin>>q;
	while(q--)
	{
		string s;
		int u,v,t;
		cin>>s;
		if(s[0]=='C')
		{
			cin>>u>>t;
			add(u,1,t);
		}
		else if(s[1]=='M')
		{
			cin>>u>>v;
			cout<<_max(u,v)<<endl;
		}
		else
		{
			cin>>u>>v;
			cout<<sum(u,v)<<endl;
		}
	}
}
2023/5/15 20:47
加载中...