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]<<" ";
	
	
}
相关推荐
anlogic1 分钟前
Java基础 9.10
java·开发语言·算法
薛定谔的算法4 分钟前
JavaScript单链表实现详解:从基础到实践
数据结构·算法·leetcode
CoovallyAIHub13 分钟前
CostFilter-AD:用“匹配代价过滤”刷新工业质检异常检测新高度! (附论文和源码)
深度学习·算法·计算机视觉
幻奏岚音14 分钟前
《数据库系统概论》第一章 初识数据库
数据库·算法·oracle
你好,我叫C小白14 分钟前
贪心算法(最优装载问题)
算法·贪心算法·最优装载问题
CoovallyAIHub21 分钟前
CVPR 2025 | 频率动态卷积(FDConv):以固定参数预算实现频率域自适应,显著提升视觉任务性能
深度学习·算法·计算机视觉
mit6.82425 分钟前
[rStar] 解决方案节点 | `BaseNode` | `MCTSNode`
人工智能·python·算法
on_pluto_1 小时前
Leecode hot100 - 448. 找到所有数组中消失的数字
数据结构
zl_dfq1 小时前
数据结构 之 【布隆过滤器 的简介】
数据结构
晴空闲雲2 小时前
数据结构与算法-树和二叉树-二叉树的存储结构(Binary Tree)
数据结构·算法