博客
关于我
【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/

你可能感兴趣的文章
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>