HDU6065 RXD, tree and sequence (DP+LCA)
来源:互联网 发布:数据漫游什么时候打开 编辑:程序博客网 时间:2024/06/11 08:57
HDU6065 RXD, tree and sequence (DP+LCA)
题目大意
给一颗树和一个全排列,把全排列恰好分成连续的k段。求每一段的公共祖先的深度的LCM的最小值
题目分析
读错题系列,读成求LCA编号的LCM,其实是求LCA深度的和。
这篇博文不错。
学习题解用时22分钟,Code用时28分钟,一次AC。
代码
#include <stdio.h>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 300100;const int M = 30;const ll INF = 1e12;struct Edge{ int u, v, nxt;}e[2 * maxn];int p[maxn], head[maxn], e_cnt, pa[maxn][M], deep[maxn], f[maxn];ll dp[maxn][2];void Add(int u, int v){ int id = e_cnt++; e[id].u = u; e[id].v = v; e[id].nxt = head[u]; head[u] = id;}void DFS(int u, int fa){ pa[u][0] = fa; for(int i = 1; i < M; i++) pa[u][i] = pa[pa[u][i-1]][i-1]; deep[u] = u == 1 ? 1 : deep[fa] + 1; for(int id = head[u]; id != -1; id = e[id].nxt) if(e[id].v != fa) DFS(e[id].v, u);}int LCA(int u, int v){ if(deep[u] > deep[v]) swap(u, v); for(int i = M - 1; i >= 0; i--) if(((deep[v] - deep[u]) >> i) & 1) v = pa[v][i]; for(int i = M - 1; i >= 0; i--) if(pa[u][i] != pa[v][i]){ u = pa[u][i]; v = pa[v][i]; } return u == v ? u : pa[u][0];}int main(){ int n, k; while(scanf("%d%d", &n, &k) == 2){ for(int i = 1; i <= n; i++) scanf("%d", &p[i]); for(int i = 1; i <= n; i++) head[i] = -1; e_cnt = 0; for(int i = 1; i < n; i++){ int u, v; scanf("%d%d", &u, &v); Add(u, v); Add(v, u); } DFS(1, 1); for(int i = 2; i <= n; i++) f[i] = deep[LCA(p[i], p[i - 1])]; for(int i = 1; i <= n; i++) dp[i][1] = i == 1 ? deep[p[i]] : min(dp[i-1][1], (ll)f[i]); for(int j = 2, t = 0; j <= k; j++, t ^= 1) for(int i = 1; i <= n; i++){ dp[i][t] = i == 1 ? INF : min(dp[i-1][t], dp[i-1][t^1] + deep[p[i]]); if(i > 2) dp[i][t] = min(dp[i][t], dp[i-2][t^1] + f[i]); } printf("%lld\n", dp[n][k % 2]); } return 0;}
反思
Tarjan求LCA?
读错题。
DP不够熟练。
阅读全文
0 0
- HDU6065 RXD, tree and sequence (DP+LCA)
- [HDU6065] RXD, tree and sequence
- HDU-6065 RXD, tree and sequence(dp+LCA)
- HDU 6065 RXD, tree and sequence(在线倍增LCA+CDQ分治+离线tarjan-LCA+dp)
- 2017多校第3场 HDU 6065 RXD, tree and sequence LCA,DP
- HDU 6065 RXD, tree and sequence DP 减少转移情况
- HDU 6065 RXD, tree and sequence (LCA, 2017 Multi-Univ Training Contest 3)
- HDU 6065 RXD, tree and sequence 分析+01背包
- HDU6060-RXD and dividing 简单树形DP+贪心
- HDU 6060 RXD and dividing(树形DP+贪心)
- 【HDU】5293 Tree chain problem【DP+LCA】
- 【HDU】5156 Harry and Christmas tree 【lca】
- 【LCA】 HDOJ 5156 Harry and Christmas tree
- HDU6060-RXD and dividing
- RXD and math HDU
- RXD and math
- HDU6063-RXD and math
- hdu6063-RXD and math
- 算法第四版第一章练习1.4.15 3_sum的O(n²)解法
- JIRA 7.3.8 项目管理搭建
- Makefile中头文件包含
- log4j2按日期按级别的日志文件归档(限制文件大小,限制每天的文件个数(10))
- LINUX下挂载(mount)查看树莓派镜像文件
- HDU6065 RXD, tree and sequence (DP+LCA)
- 【深度学习】谷歌deepdream原理及tensorflow实现
- Laya学习笔记-Sprite-1.7.10
- 使用API扩展应用功能必会的方法
- 【数论】[NOIP2014]螺旋矩阵
- 我的第一篇博客(好紧张)
- Android7.0RecyclerView用法解析
- 为开发者赋能,阿里云大学人才培养再次升级
- 从零开始学Scala(一)——Scala环境搭建与第一行代码