Codeforces 1324F. Maximum White Subtree(树形DP)

Description

You are given a tree consisting of n vertices. A tree is a connected undirected graph with n−1 edges. Each vertex v of this tree has a color assigned to it (av=1 if the vertex v is white and 0 if the vertex v is black).

You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntw white vertices and cntb black vertices, you have to maximize cntw−cntb.

Input

The first line of the input contains one integer n (2≤n≤2⋅105) — the number of vertices in the tree.

The second line of the input contains n integers a1,a2,…,an (0≤ai≤1), where ai is the color of the i-th vertex.

Each of the next n−1 lines describes an edge of the tree. Edge i is denoted by two integers ui and vi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi).

It is guaranteed that the given edges form a tree.

Output

Print n integers res1,res2,…,resn, where resi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i.

Examples
input

9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9

output

2 2 2 2 2 1 1 0 2

input

4
0 0 1 0
1 2
1 3
1 4

output

0 -1 1 -1

题目大意

给出一颗树以及每个节点的颜色,对每一个顶点i求包含顶点i的子树的最大差异(白色顶点减黑色顶点数量的最大值)

思路

两遍dfs,第一遍dfs自底向上求以当前节点为根节点的最大差异(白色顶点减黑色顶点数量的最大值)
(如果子树的白色顶点减黑色顶点数量的最大值大于0就加上)
第二遍dfs自顶向下求包含当前节点的子树的最大差异(白色顶点减黑色顶点数量的最大值)
(如果子节点为正,说明父节点的最大差异有这个子树的贡献,递归的时候减去)

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=2e5+5;
int a[maxn],v[maxn],head[maxn],cnt;
struct node{
	int to,next;
}edge[maxn<<1];
void add(int a,int b){
	edge[++cnt].to=b;
	edge[cnt].next=head[a];
	head[a]=cnt;
}
int dfs(int now,int f){
	v[now]=a[now]?1:-1;
	for(int i=head[now];i!=-1;i=edge[i].next){
		int to=edge[i].to;
		if(to==f)continue;
		v[now]+=max(0,dfs(to,now));
	}
	return v[now];
}
int dfs_(int now,int f,int fa_v){
	if(fa_v>0)v[now]+=fa_v;
	for(int i=head[now];i!=-1;i=edge[i].next){
		int to=edge[i].to;
		if(to==f)continue;
		dfs_(to,now,v[now]-max(0,v[to]));
	}
}
int main()
{
	int n;
	scanf("%d",&n);
	memset(head,-1,sizeof(head));
	for(int i=1;i<=n;++i)
		scanf("%d",&a[i]);
	for(int i=1;i<n;++i){
		int u,v;
		scanf("%d %d",&u,&v);
		add(u,v),add(v,u);
	}
	dfs(1,0);
	dfs_(1,0,0);
	for(int i=1;i<=n;++i){
		printf("%d%c",v[i],i==n?'\n':' ');
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值