P1122 最大子树和

题目描述

小明对数学饱有兴趣,并且是个勤奋好学的学生,总是在课后留在教室向老师请教一些问题。一天他早晨骑车去上课,路上见到一个老伯正在修剪花花草草,顿时想到了一个有关修剪花卉的问题。于是当日课后,小明就向老师提出了这个问题:

一株奇怪的花卉,上面共连有 n 朵花,共有 n−1 条枝干将花儿连在一起,并且未修剪时每朵花都不是孤立的。每朵花都有一个"美丽指数",该数越大说明这朵花越漂亮,也有"美丽指数"为负数的,说明这朵花看着都让人恶心。所谓"修剪",意为:去掉其中的一条枝条,这样一株花就成了两株,扔掉其中一株。经过一系列"修剪"之后,还剩下最后一株花(也可能是一朵)。老师的任务就是:通过一系列"修剪"(也可以什么"修剪"都不进行),使剩下的那株(那朵)花卉上所有花朵的"美丽指数"之和最大。

老师想了一会儿,给出了正解。小明见问题被轻易攻破,相当不爽,于是又拿来问你。

输入格式

第一行一个整数 n (1≤n≤16000)。表示原始的那株花卉上共 n 朵花。

第二行有 n 个整数,第 i 个整数表示第 i 朵花的美丽指数。

接下来 n−1 行每行两个整数 a,b,表示存在一条连接第 a 朵花和第 b 朵花的枝条。

输出格式

一个数,表示一系列"修剪"之后所能得到的"美丽指数"之和的最大值。保证绝对值不超过 2147483647。

输入输出样例

输入 #1

复制代码
7
-1 -1 -1 1 1 1 0
1 4
2 5
3 6
4 7
5 7
6 7

输出 #1

复制代码
3

树形dp


cpp 复制代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define  mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;

const int N = 200086, mod = 998244353;

int n, m;
int h[N], e[N], ne[N], idx;
int f[N];
int res = -inf;

void add(int a, int b) {
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx++;
}

void dfs(int u, int fa) {

    for (int i = h[u]; ~i; i = ne[i]) {
        int son = e[i];
        if (son == fa) continue;
        dfs(son, u);
        f[u] += max(0ll, f[son]);
        res = max(res, f[u]);
    }
}

void solve() {
    mst(h, -1);
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> f[i];
    
    for (int i = 1; i < n; i++) {
        int a, b;
        cin >> a >> b;
        add(a, b);
        add(b, a);
    }
    
    dfs(1, -1);
    cout << res << endl;
    
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    int T = 1;
// cin >> T;
    while (T--) solve();
    
    return 0;
}
相关推荐
郝学胜-神的一滴2 小时前
深入浅出 C++20:新特性与实践
开发语言·c++·程序人生·算法·c++20
Jelena技术达人2 小时前
淘宝/天猫按图搜索(拍立淘)item_search_img API接口实战指南
算法·图搜索算法
Adorable老犀牛2 小时前
阿里云-基于通义灵码实现高效 AI 编码 | 8 | 上手实操:LeetCode学习宝典,通义灵码赋能算法高效突破
学习·算法·leetcode
望获linux2 小时前
【实时Linux实战系列】规避缺页中断:mlock/hugetlb 与页面预热
java·linux·服务器·数据库·chrome·算法
菜就多练,以前是以前,现在是现在3 小时前
Codeforces Round 1048 (Div. 2)
数据结构·c++·算法
林木辛3 小时前
LeetCode 热题 160.相交链表(双指针)
算法·leetcode·链表
野生的编程萌新3 小时前
【C++深学日志】从0开始的C++生活
c语言·开发语言·c++·算法
ulias2124 小时前
单元最短路问题
数据库·c++·算法·动态规划
崎岖Qiu4 小时前
leetcode380:RandomizedSet - O(1)时间插入删除和获取随机元素(数组+哈希表的巧妙结合)
java·数据结构·算法·leetcode·力扣·散列表