1220. 生命之树

题目链接

1220. 生命之树

给一棵树和每个结点的权值,求联通块的最大权值和

输入格式

第一行一个整数 n 表示这棵树有 n 个节点。

第二行 n 个整数,依次表示每个节点的权值。

接下来 n1 行,每行 2 个整数 u,v,表示存在一条 uv 的边。

由于这是一棵树,所以是不存在环的。

树的节点编号从 1n

输出格式

输出一行一个数,表示联通块的最大权值和。

数据范围

1n105,
每个节点的评分的绝对值均不超过 106

输入样例:

5 1 -2 -3 4 5 4 2 3 1 1 2 2 5

输出样例:

8

解题思路

dfs

直接用dfs求出包含某个节点的子树的最大权值和,权值和为负数取 0 即可
当然也可以认为是一种树形dp,即:

  • 状态表示:f[i] 表示包含 i 的子树的最大权值和

  • 状态计算:f[i]=w[i]+i>jmax(0,f[j])

  • 时间复杂度:(n+m)

代码

// Problem: 生命之树 // Contest: AcWing // URL: https://www.acwing.com/problem/content/1222/ // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> //#define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } const int N=100005; vector<int> adj[N]; int n,w[N]; LL res=-1e18; LL dfs(int x,int fa) { LL t=w[x]; for(auto y:adj[x]) { if(y==fa)continue; t+=max(0ll,dfs(y,x)); } res=max(res,t); return t; } int main() { cin>>n; for(int i=1;i<=n;i++) cin>>w[i]; for(int i=1;i<n;i++) { int x,y; cin>>x>>y; adj[x].pb(y); adj[y].pb(x); } dfs(1,0); cout<<res; return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/15902268.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示