博客
关于我
【nowcoder 217042】CCA的子树
阅读量:331 次
发布时间:2019-03-04

本文共 1535 字,大约阅读时间需要 5 分钟。

CCA的子树

题目链接:

到牛客看:

题目大意

有一个带点权的树,根节点是 1 1 1

要你选出两个点,它们不会一个是另一个的祖先,然后你要让它们子树点权和的和最大。
如果不能选出两个点,就输出 Error

思路

我们可以想到这题应该是树形 DP。

考虑先 DP 出某个点的子树的点权和 q i q_i qi,然后可以想到用这样一种方法。

我们在 DP 出某个点的子树中的每个点 x x x q x q_x qx 值的最大值 b i g _ s o n i big\_son_i big_soni
那我们考虑枚举你选的两个点的最近公共祖先,然后就把它子树的 b i g _ s o n big\_son big_son 值最大的两个相加,得到的就是这个点为最近公共祖先时答案能有的最大值。

那你就把所有的取一个最大值,就可以了。

代码

#include
#include
#define ll long longusing namespace std;struct node { int to, nxt;}e[400001];int n, a[200001], x, y;int KK, le[200001], maxn_dep;ll ans, big_son[200001], sum[200001];void add(int x, int y) { e[++KK] = (node){ y, le[x]}; le[x] = KK; }void dfs(int now, int father, int dep) { maxn_dep = max(maxn_dep, dep); big_son[now] = -0x3f3f3f3f3f3f3f3f; sum[now] = a[now]; ll maxn = -0x3f3f3f3f3f3f3f3f, maxn2 = -0x3f3f3f3f3f3f3f3f; for (int i = le[now]; i; i = e[i].nxt) if (e[i].to != father) { dfs(e[i].to, now, dep + 1); big_son[now] = max(big_son[now], big_son[e[i].to]); sum[now] += sum[e[i].to]; if (big_son[e[i].to] > maxn) { maxn2 = maxn; maxn = big_son[e[i].to]; } else if (big_son[e[i].to] > maxn2) maxn2 = big_son[e[i].to]; } big_son[now] = max(big_son[now], sum[now]); ans = max(ans, maxn + maxn2);}int main() { ans = -0x3f3f3f3f3f3f3f3f; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i < n; i++) { scanf("%d %d", &x, &y); add(x, y); add(y, x); } dfs(1, 0, 1); if (maxn_dep == n) printf("Error"); else printf("%lld", ans); return 0;}

转载地址:http://frvh.baihongyu.com/

你可能感兴趣的文章
mysql主从复制 master和slave配置的参数大全
查看>>
MySQL主从复制几个重要的启动选项
查看>>
MySQL主从复制及排错
查看>>
mysql主从复制及故障修复
查看>>
MySQL主从复制的原理和实践操作
查看>>
webpack loader配置全流程详解
查看>>
mysql主从复制,读写分离,半同步复制实现
查看>>
MySQL主从失败 错误Got fatal error 1236解决方法
查看>>
MySQL主从架构与读写分离实战
查看>>
MySQL主从篇:死磕主从复制中数据同步原理与优化
查看>>
mysql主从配置
查看>>
MySQL之2003-Can‘t connect to MySQL server on ‘localhost‘(10038)的解决办法
查看>>
MySQL之CRUD
查看>>
MySQL之DML
查看>>
Mysql之IN 和 Exists 用法
查看>>
MYSQL之REPLACE INTO和INSERT … ON DUPLICATE KEY UPDATE用法
查看>>
MySQL之SQL语句优化步骤
查看>>
MYSQL之union和order by分析([Err] 1221 - Incorrect usage of UNION and ORDER BY)
查看>>
Mysql之主从复制
查看>>