WA求助
查看原帖
WA求助
531829
EricZiyiWang楼主2021/11/16 21:45
#include<bits/stdc++.h>
using namespace std;
const int maxm=1e7+10;
int n,q,x,y,cnt,head[maxm],w[maxm],c[maxm];
int sum,tot,dep[maxm],siz[maxm],top[maxm],fa[maxm],son[maxm],id[maxm],val[maxm];
int dat1[maxm],dat2[maxm],Lpos[maxm],Rpos[maxm],R[maxm];
string opt;
struct edge
{
	int next,to;
}e[maxm];
void add(int u,int v)
{
	e[++cnt].next=head[u];
	e[cnt].to=v;
	head[u]=cnt;
}
void dfs1(int u)
{
	siz[u]=1;
	for(int i=head[u];i;i=e[i].next)
	{
		int v=e[i].to;
		if(dep[v]) continue;
		dep[v]=dep[u]+1;
		fa[v]=u;
		dfs1(v);
		siz[u]+=siz[v];
		if(siz[v]>siz[son[u]]) son[u]=v;
	}
}
void dfs2(int u,int topf)
{
	id[u]=++tot;
	val[tot]=u;
	top[u]=topf;
	if(!son[u]) return;
	dfs2(son[u],topf);
	for(int i=head[u];i;i=e[i].next)
	{
		int v=e[i].to;
		if(v==fa[u]||v==son[u]) continue;
		dfs2(v,v);
	}
}
#define Mid ((l+r)>>1)
#define Lpos Lpos[pos]
#define Rpos Rpos[pos]
#define Lson Lpos,l,Mid
#define Rson Rpos,Mid+1,r
void upd(int pos)
{
	dat1[pos]=dat1[Lpos]+dat2[Rpos];
	dat2[pos]=max(dat2[Lpos],dat2[Rpos]);
}
void upd(int &pos,int l,int r,int x,int v)
{
	if(!pos) pos=++sum;
	if(l==r) return dat1[pos]=dat2[pos]=v,void();
	if(x<=Mid) upd(Lson,x,v);
	if(x>=Mid+1) upd(Rson,x,v);
	upd(pos);
}
void era(int &pos,int l,int r,int x)
{
	if(!pos) return;
	if(l==r) return dat1[pos]=dat2[pos]=0,void();
	if(x<=Mid) era(Lson,x);
	if(x>=Mid+1) era(Rson,x);
	upd(pos);
}
int qry1(int &pos,int l,int r,int L,int R)
{
	if(!pos) return 0;
	if(L<=l&&r<=R) return dat1[pos];
	if(R<=Mid) return qry1(Lson,L,R);
	if(L>=Mid+1) return qry1(Rson,L,R);
	return qry1(Lson,L,R)+qry1(Rson,L,R);
}
int qry2(int &pos,int l,int r,int L,int R)
{
	if(!pos) return 0;
	if(L<=l&&r<=R) return dat2[pos];
	if(R<=Mid) return qry2(Lson,L,R);
	if(L>=Mid+1) return qry2(Rson,L,R);
	return max(qry2(Lson,L,R),qry2(Rson,L,R));
}
int main()
{
	cin>>n>>q;
	for(int i=1;i<=n;++i)
		cin>>w[i]>>c[i];
	for(int i=1;i<n;++i)
	{
		cin>>x>>y;
		add(x,y);
		add(y,x);
	}
	dep[1]=1;
	dfs1(1);
	dfs2(1,1);
	for(int i=1;i<=n;++i)
		upd(R[c[val[i]]],1,n,i,w[val[i]]);
	for(int i=1;i<=q;++i)
	{
		cin>>opt>>x>>y;
		if(opt=="CC")
		{
			era(R[c[x]],1,n,id[x]);
			c[x]=y;
			upd(R[c[x]],1,n,id[x],w[x]);
		}
		if(opt=="CW")
		{
			era(R[c[x]],1,n,id[x]);
			w[x]=y;
			upd(R[c[x]],1,n,id[x],w[x]);
		}
		if(opt=="QS")
		{
			int ans=0,k=c[x];
			while(top[x]!=top[y])
			{
				if(dep[top[x]]<dep[top[y]]) swap(x,y);
				ans+=qry1(R[k],1,n,id[top[x]],id[x]);
				x=fa[top[x]];
			}
			if(dep[x]>dep[y]) swap(x,y);
			ans+=qry1(R[k],1,n,id[x],id[y]);
			cout<<ans<<endl;
		}
		if(opt=="QM")
		{
			int ans=0,k=c[x];
			while(top[x]!=top[y])
			{
				if(dep[top[x]]<dep[top[y]]) swap(x,y);
				ans=max(ans,qry2(R[k],1,n,id[top[x]],id[x]));
				x=fa[top[x]];
			}
			if(dep[x]>dep[y]) swap(x,y);
			ans=max(ans,qry2(R[k],1,n,id[x],id[y]));
			cout<<ans<<endl;
		}
	}
	return 0;
}
2021/11/16 21:45
加载中...