洛谷P3038 [USACO11DEC] Grass Planting G 题解 树链剖分
题目链接:https://www.luogu.com.cn/problem/P3038
题目大意:
一棵树维护两种操作:
- 一条路径上每条边边权 \(+1\);
- 查询路径上的边权和。
解题思路:
树链剖分模板题。
示例程序:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int fa[maxn], dep[maxn], size[maxn], son[maxn], top[maxn], seg[maxn], rev[maxn];
int n, m, seg_cnt;
vector<int> g[maxn];
void dfs1(int u, int p) {
size[u] = 1;
for (auto v : g[u]) {
if (v != p) {
fa[v] = u;
dep[v] = dep[u] + 1;
dfs1(v, u);
size[u] += size[v];
if (size[v] > size[son[u]])
son[u] = v;
}
}
}
void dfs2(int u, int tp) {
seg[u] = ++seg_cnt;
rev[seg_cnt] = u;
top[u] = tp;
if (son[u])
dfs2(son[u], tp);
for (auto v : g[u])
if (v != fa[u] && v != son[u])
dfs2(v, v);
}
long long tr[maxn<<2];
int lazy[maxn<<2];
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1
void push_up(int rt) {
tr[rt] = tr[rt<<1] + tr[rt<<1|1];
}
void push_down(int l, int r, int rt) {
int mid = (l + r) / 2;
if (lazy[rt]) {
tr[rt<<1] += (long long) (mid - l + 1) * lazy[rt];
lazy[rt<<1] += lazy[rt];
tr[rt<<1|1] += (long long) (r - mid) * lazy[rt];
lazy[rt<<1|1] += lazy[rt];
lazy[rt] = 0;
}
}
long long query(int L, int R, int l, int r, int rt) {
if (L <= l && r <= R) return tr[rt];
int mid = (l + r) / 2;
push_down(l, r, rt);
long long res = 0;
if (L <= mid) res += query(L, R, lson);
if (R > mid) res += query(L, R, rson);
return res;
}
void update(int L, int R, int val, int l, int r, int rt) {
if (L <= l && r <= R) {
lazy[rt] += val;
tr[rt] += (long long) val * (r - l + 1);
return;
}
push_down(l, r, rt);
int mid = (l + r) / 2;
if (L <= mid) update(L, R, val, lson);
if (R > mid) update(L, R, val, rson);
push_up(rt);
}
long long func_query(int u, int v) {
long long res = 0;
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(u, v);
res += query(seg[top[u]], seg[u], 1, n, 1);
u = fa[top[u]];
}
if (dep[u] < dep[v]) swap(u, v);
if (u != v)
res += query(seg[v] + 1, seg[u], 1, n, 1);
return res;
}
void func_update(int u, int v) {
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(u, v);
update(seg[top[u]], seg[u], 1, 1, n, 1);
u = fa[top[u]];
}
if (dep[u] < dep[v]) swap(u, v);
if (u != v)
update(seg[v] + 1, seg[u], 1, 1, n, 1);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i < n; i++) {
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
}
dfs1(1, -1);
dfs2(1, 1);
while (m--) {
char op[2];
int u, v;
scanf("%s%d%d", op, &u, &v);
if (op[0] == 'P') {
func_update(u, v);
}
else {
long long ans = func_query(u, v);
printf("%lld\n", ans);
}
}
return 0;
}