博客
关于我
【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 内连接、自然连接、外连接的区别
查看>>
mysql 写入慢优化
查看>>
mysql 分组统计SQL语句
查看>>
Mysql 分页
查看>>
Mysql 分页语句 Limit原理
查看>>
MySQL 创建新用户及授予权限的完整流程
查看>>
mysql 创建表,不能包含关键字values 以及 表id自增问题
查看>>
mysql 删除日志文件详解
查看>>
mysql 判断表字段是否存在,然后修改
查看>>
mysql 协议的退出命令包及解析
查看>>
mysql 取表中分组之后最新一条数据 分组最新数据 分组取最新数据 分组数据 获取每个分类的最新数据
查看>>
mysql 多个表关联查询查询时间长的问题
查看>>
mySQL 多个表求多个count
查看>>
mysql 多字段删除重复数据,保留最小id数据
查看>>
MySQL 多表联合查询:UNION 和 JOIN 分析
查看>>
MySQL 大数据量快速插入方法和语句优化
查看>>
mysql 如何给SQL添加索引
查看>>
mysql 字段区分大小写
查看>>
mysql 字段合并问题(group_concat)
查看>>
mysql 字段类型类型
查看>>