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]<<" ";
	
	
}
相关推荐
我是伪码农3 分钟前
11.21程序设计
数据结构·算法
Tisfy1 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
羊在吃青草1 小时前
C语言之数组
c语言·数据结构
灯澜忆梦1 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
专注仿真2 小时前
达梦数据库 SQL 优化实战:从执行计划到索引、统计信息与参数调优
数据结构·数据库·数据库开发·数据库架构
Shaoshing2 小时前
LeetCode100 155.最小栈
java·数据结构·算法
秋天的怀念_David3 小时前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
纪念 2293 小时前
C++ 算法模板与错题 (差分)
开发语言·c++·算法