F. Maximum White Subtree

换根DP好题

题目大意:一棵树,节点有黑有白,从某节点出发,遇黑-1,遇白+1。
问:从每个节点出发,能得到的最大值是多少?

直接换根就好了,第一遍扫的时候,子树为正就算上,

第二遍down的时候 对u->v的边,我们看看v有没有对u做贡献,有的话直接删去它的贡献

看看u剩下的能对v做不做贡献就好了

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
vector<int>g[N];
int ans[N],dp[N];
int n;
int c[N];
int res;
void dfs(int u,int father){
	dp[u] = c[u]?1:-1;
	for(auto &t:g[u]){
		if(t==father)continue;
		dfs(t,u);
		if(dp[t]>0)dp[u]+=dp[t];
	}

}


void down(int u,int father){
	for(auto t:g[u]){
		if(t==father)continue;
		int from = dp[u],to =dp[t];
		if(to>0)from-=to;
		if(from>0)to+=from;
		dp[t] = to;
		
		down(t,u);
		
		
	}
}


int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)cin>>c[i];
	
	for(int i=1;i<n;++i){
		int a,b;cin>>a>>b;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	
	dfs(1,-1);
	
	down(1,-1);
	
	for(int i=1;i<=n;i++)cout<<dp[i]<<" ";
	
	
}
相关推荐
Ada's4 小时前
【计算机基础系列】003:Python数据结构
开发语言·数据结构·python
Nil2085 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
wanderist.7 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
All for pursuit.8 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
weixin_307779138 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
青少儿编程课堂8 小时前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
光影少年8 小时前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法
HEJOO99 小时前
Linux 设备驱动系列——使用全局工作队列
java·linux·算法
Code_Solitude9 小时前
c语言:递归
java·c语言·算法
程序员清风9 小时前
哈希表:从键值映射到高效查找
数据结构·哈希算法·散列表