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]<<" ";
	
	
}
相关推荐
tianyu23426 分钟前
HashMap 灵魂 30 问:从数据结构到红黑树,从扩容到 ConcurrentHashMap,一篇彻底通关
数据结构·hashmap·hashset·linkedhashmap‌
阳明山水1 小时前
Mamba与两阶段XGBoost的融合架构:面向间歇性需求的双路径预测框架
人工智能·深度学习·算法·机器学习·架构
水上冰石1 小时前
【MuJoCo从入门到精通】第2章 第一个 MuJoCo 仿真
前端·人工智能·算法
wenyq71 小时前
LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String
算法·leetcode
维克兜率天1 小时前
【维克】技术指标是什么:从均线到MACD的数学原理
人工智能·笔记·python·算法·量化
Messy create1 小时前
【储能系统三大核心】
网络·stm32·单片机·算法·能源
sel_91 小时前
【vLLM】vLLM 推理框架详解:从 PagedAttention 到生产级部署实战
人工智能·深度学习·算法·语言模型·框架·vllm
XR1234567882 小时前
办公大楼组网选型决策树:TCO 与三大品牌优劣对比总结
算法·决策树·机器学习
阳明山水2 小时前
Mamba路径如何建模长程时序依赖
人工智能·深度学习·算法·机器学习·架构
_Narcissus_3 小时前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治