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]<<" ";
	
	
}
相关推荐
hanlin038 分钟前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.28 分钟前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
碧海银沙音频科技研究院3 小时前
基于炬芯ATS3089X自研AEC声学回声消除算法
算法
通问AI3 小时前
在两台 Mac Studio 上跑 800B 模型:MLX + RDMA over Thunderbolt 实测与四道门选型法
算法
ZywOo6233 小时前
《算法竞赛进阶指南》0x03 前缀和与差分
算法
Scintilla_y3 小时前
DAY2 滑动窗口
算法·leetcode·散列表
lvwangshu3 小时前
笛卡尔树
算法·图论
026d234 小时前
状态信号只知“其然”不知“其所以然”:变工况机械故障诊断的物理盲区
算法
姜鱼问生4 小时前
备份和服务器在同一台机器上,等于没备份
算法·架构
姜鱼问生4 小时前
别再 chmod 777 了,用 ACL 给它开一扇窗
后端·算法·架构