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]<<" ";
	
	
}
相关推荐
算家计算7 分钟前
突然发布!GPT-5.2深夜来袭,3个版本碾压人类专家,打工人该怎么选?
算法·openai·ai编程
s09071361 小时前
Xilinx FPGA 中ADC 数据下变频+ CIC 滤波
算法·fpga开发·fpga·zynq
TL滕2 小时前
从0开始学算法——第十二天(KMP算法练习)
笔记·学习·算法
Math_teacher_fan2 小时前
第二篇:核心几何工具类详解
人工智能·算法
汉克老师2 小时前
CCF-NOI2025第二试题目与解析(第二题、集合(set))
c++·算法·noi·子集卷积·sos dp·mod 异常
mit6.8243 小时前
presum|
算法
不穿格子的程序员3 小时前
从零开始写算法——链表篇2:从“回文”到“环形”——链表双指针技巧的深度解析
数据结构·算法·链表·回文链表·环形链表
guygg883 小时前
基于Matlab的压缩感知信道估计算法实现
开发语言·算法·matlab