当前位置: 首页 > news >正文

树链剖分/轻重链剖分

基础封装(配合线段树等数据结构使用)

本封装将线段树处理的部分分离,方便修改。支持模板题P3384 【模板】重链剖分/树链剖分的四个查询(链上查询/修改、子树查询/修改),建树时间复杂度 O(Nlog⁡N)\mathcal O(N\log N) ,单次查询时间复杂度 O(log2⁡N)\mathcal O(\log ^2 N) 。

struct HLD {int n, idx;vector<vector<int>> ver;vector<int> siz, dep;vector<int> top, son, parent;vector<int> in, id, val;Segt segt;HLD(int n) {this->n = n;ver.resize(n + 1);siz.resize(n + 1);dep.resize(n + 1);top.resize(n + 1);son.resize(n + 1);parent.resize(n + 1);idx = 0;id.resize(n + 1);val.resize(n + 1);}void add(int x, int y) { // 建立双向边ver[x].push_back(y);ver[y].push_back(x);}void dfs1(int x) {siz[x] = 1;dep[x] = dep[parent[x]] + 1;for (auto y : ver[x]) {if (y == parent[x]) continue;parent[y] = x;dfs1(y);siz[x] += siz[y];if (siz[y] > siz[son[x]]) {son[x] = y;}}}void dfs2(int x, int up) {id[x] = ++idx;val[idx] = in[x]; // 建立编号top[x] = up;if (son[x]) dfs2(son[x], up);for (auto y : ver[x]) {if (y == parent[x] || y == son[x]) continue;dfs2(y, y);}}void work(int root, auto in) { // 在此初始化this->in = in;dfs1(root);dfs2(root, root);segt.init(val); // 建立线段树}void modify(int l, int r, int val) { // 链上修改while (top[l] != top[r]) {if (dep[top[l]] < dep[top[r]]) {swap(l, r);}segt.modify(id[top[l]], id[l], val);l = parent[top[l]];}if (dep[l] > dep[r]) {swap(l, r);}segt.modify(id[l], id[r], val);}void modify(int root, int val) { // 子树修改segt.modify(id[root], id[root] + siz[root] - 1, val);}int ask(int l, int r) { // 链上查询int ans = 0;while (top[l] != top[r]) {if (dep[top[l]] < dep[top[r]]) {swap(l, r);}ans += segt.ask(id[top[l]], id[l]);l = parent[top[l]];}if (dep[l] > dep[r]) {swap(l, r);}return ans + segt.ask(id[l], id[r]);}int ask(int root) { // 子树查询return segt.ask(id[root], id[root] + siz[root] - 1);}
};

模板题

P3384 【模板】重链剖分/树链剖分

http://www.gsyq.cn/news/28813.html

相关文章:

  • 每日反思(2025_10_23)
  • C#编程时winform程序登陆记住密码和自动登录功能,关于App.config的问题及解决方案
  • [C/C++] Linux 环境变量(C/C++ ver)
  • 【题解】P14254 分割(divide)
  • Day2路径,相对与绝对
  • 第九届强网杯线上赛PWN_flag-market
  • ISFB银行木马家族演化史:从Gozi到LDR4的技术剖析
  • exgcd板子
  • 编程练习
  • Codeforces Round 976 (Div. 2) A. Find Minimum Operations
  • 20251021 NOIP模拟赛
  • RocketMQ+Spring Boot的简单实现及其深入分析
  • XSD 文档(XML Schema Definition)简介
  • LLM 场景下的强化学习技术扫盲
  • vmware虚拟机下载安装教程(付安装包)详细图文下载安装教程
  • deepin 25 虚拟机安装vgpu客户机驱动
  • CF2153D
  • 英语_阅读_inspiration for artists_待读
  • Node.js JSON import attributes All In One
  • DeepSeek的“认知提纯”能力解析
  • Plya 定理学习笔记 | ABC428G 题解
  • 告别繁琐排版!揭秘2025年公众号推文排版top1神器
  • leetcode1. 两数之和、15. 三数之和、18. 四数之和
  • vue3+elementPlus el-date-picker 自定义禁用状态hook 建立结束时间不能小于开始时间
  • 【做题记录】贪心--提高组
  • 【为美好CTF献上祝福】 New Star 2025 逆向笔记
  • XXL-JOB(5)
  • Ramanujan Master Theorem
  • 【周记】2025.10.13~2025.10.19
  • C++案例 自定义数组