小样例过不了,求条
查看原帖
小样例过不了,求条
886055
MoonCake2011楼主2024/12/25 13:26
#include<bits/stdc++.h>
using namespace std;
int n,m;
struct Matrix{
	int m[2][2];
	Matrix(){m[0][0]=m[0][1]=m[1][0]=m[1][1]=-INT_MAX;}
	inline Matrix(int a,int b){m[0][0]=m[0][1]=a,m[1][0]=b,m[1][1]=-INT_MAX;}
};
inline Matrix operator * (Matrix x,Matrix y){
	Matrix c;
	for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) c.m[i][j]=max(c.m[i][j],x.m[i][k]+y.m[k][j]);
	return c;
}
int a[100010];
Matrix v[100010];
int dp[100010][2],f[100010][2];
int head[100010],to[200010],nxt[200010],tot;
void add(int u,int v){
	to[++tot]=v;
	nxt[tot]=head[u];
	head[u]=tot;
}
int fa[100010],son[100010],siz[100010],dep[100010];
void dfs1(int x,int f){
	fa[x]=f,siz[x]=1,dp[x][1]=a[x];
	for(int i=head[x];i;i=nxt[i]){
		if(to[i]==f) continue;
		dep[to[i]]=dep[x]+1;
		dfs1(to[i],x);
		dp[x][0]+=max(dp[to[i]][0],dp[to[i]][1]);
		dp[x][1]+=dp[to[i]][0];
		siz[x]+=siz[to[i]];
		if(siz[son[x]]<siz[to[i]]) son[x]=to[i];
	}
}
int id[100010],top[100010],ed[100010],cnt;
void dfs2(int x,int t){
	id[x]=++cnt,f[x][1]=a[x],top[x]=t,ed[t]=max(ed[t],id[x]);
	if(!son[x]) return;
	dfs2(son[x],t);
	for(int i=head[x];i;i=nxt[i]){
		if(to[i]==son[x] || to[i]==fa[x]) continue;
		f[x][0]+=max(f[to[i]][0],f[to[i]][1]);
		f[x][1]+=f[to[i]][0];
		dfs2(to[i],to[i]);
	}
	v[id[x]]=Matrix(f[x][0],f[x][1]);
}
Matrix t[400010];
void creat(int l,int r,int root){
	if(l==r){
		t[root]=v[l];
		return; 
	}
	int mid=l+r>>1;
	creat(l,mid,root*2);
	creat(mid+1,r,root*2+1);
	t[root]=t[root*2]*t[root*2+1];
}
void update(int u,Matrix v,int x=1,int y=n,int root=1){
	if(x==y && u==x){
		t[root]=v;
		return;
	}
	int mid=x+y>>1;
	if(u<=mid) update(u,v,x,mid,root*2);
	else update(u,v,mid+1,y,root*2+1);
	t[root]=t[root*2]*t[root*2+1];
}
Matrix ask(int l,int r,int x=1,int y=n,int root=1){
	if(l<=x && y<=r) return t[root];
	int mid=x+y>>1;
	Matrix tot;
	if(l<=mid) tot=ask(l,r,x,mid,root*2);
	if(mid<r) tot=tot*ask(l,r,mid+1,y,root*2+1);
	return tot; 
}
Matrix update_path(int u,int w){
	v[id[u]].m[1][0]+=w-a[u],a[u]=w;
	Matrix a,b;
	while(u){
		b=ask(id[top[u]],ed[top[u]]);
		update(id[u],v[u]);
		a=ask(id[top[u]],ed[top[u]]);
		u=fa[top[u]];
		v[id[u]].m[0][0]+=max(a.m[0][0],a.m[1][0])-max(b.m[0][0],b.m[1][0]);
		v[id[u]].m[0][1]=v[id[u]].m[0][0];
		v[id[u]].m[1][0]+=a.m[0][0]-b.m[0][0];
	}
}
int ask_dp(){
	Matrix ans=ask(id[1],ed[1]);
	return max(ans.m[0][0],ans.m[1][0]);
}
signed main() {
    ios::sync_with_stdio(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<n;i++){
		int u,v;
		cin>>u>>v;
		add(u,v),add(v,u);
	}
	dfs1(1,0);
	dfs2(1,1);
	creat(1,n,1);
	while(m--){
		int u,x;
		cin>>u>>x;
		update_path(u,x);
		cout<<ask_dp()<<"\n";
	}
	return 0;
}
2024/12/25 13:26
加载中...