Codeforces - Maximum White Subtree

题目链接:Codeforces - Maximum White Subtree


比较裸的换根的,dp[x]表示子树当中最大的值即可。


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include
//#define int long long
using namespace std;
const int N=2e5+10;
int n,a[N],dp[N],f[N],res[N],vis[N],ans;
vector<int> g[N];
void dfs1(int x,int fa){
	dp[x]=(a[x]==1?1:-1);	int tmp=0;
	for(auto to:g[x]){
		if(to==fa)	continue;	dfs1(to,x);
		tmp+=max(0,dp[to]);
	}
	dp[x]+=tmp;
}
void dfs2(int x,int fa){
	for(auto to:g[x]){
		if(to==fa)	continue;
		res[to]=max(dp[to]+(res[x]-max(0,dp[to])),dp[to]);
		dfs2(to,x);
	}
}
signed main(){
	cin>>n;
	for(int i=1;i<=n;i++)	scanf("%d",&a[i]);
	for(int i=1,a,b;i<n;i++)	
		scanf("%d %d",&a,&b),g[a].push_back(b),g[b].push_back(a);
	dfs1(1,1);	res[1]=dp[1];	dfs2(1,1);
	for(int i=1;i<=n;i++)	printf("%d ",res[i]);
	return 0;
}

你可能感兴趣的:(Codeforces,树形dp)