题意
思路
我们可以使用树链剖分,将每条边的边权下放,将其当作点权处理,每次操作都要忽略 lca 那个点,因为它所对应的点并不在路径上。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
struct edge {
int to, next;
} e[N * 2];
int head[N], idx = 1;
void add(int u, int v) {
idx++;
e[idx].to = v;
e[idx].next = head[u];
head[u] = idx;
}
struct node {
int sum, add;
} tr[N << 2];
void pushup(int u) {
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void addtag(int u, int c, int l, int r) {
tr[u].add += c;
tr[u].sum += c * (r - l + 1);
}
void pushdown(int u, int l, int r) {
if (tr[u].add) {
int mid = l + r >> 1;
addtag(u << 1, tr[u].add, l, mid);
addtag(u << 1 | 1, tr[u].add, mid + 1, r);
tr[u].add = 0;
}
}
void modify(int u, int l, int r, int pl, int pr, int v) {
if (pl <= l && r <= pr) {
addtag(u, v, l, r);
return;
}
pushdown(u, l, r);
int mid = l + r >> 1;
if (pl <= mid) modify(u << 1, l, mid, pl, pr, v);
if (pr > mid) modify(u << 1 | 1, mid + 1, r, pl, pr, v);
pushup(u);
}
int query(int u, int l, int r, int pl, int pr) {
if (pl <= l && r <= pr) return tr[u].sum;
pushdown(u, l, r);
int mid = l + r >> 1, sum = 0;
if (pl <= mid) sum += query(u << 1, l, mid, pl, pr);
if (pr > mid) sum += query(u << 1 | 1, mid + 1, r, pl, pr);
return sum;
}
int son[N], sz[N], fa[N], dep[N];
void dfs1(int u, int f) {
sz[u] = 1, fa[u] = f, dep[u] = dep[f] + 1;
for (int i = head[u]; i; i = e[i].next) {
int to = e[i].to;
if (to == f) continue;
dfs1(to, u);
sz[u] += sz[to];
if (sz[son[u]] < sz[to]) son[u] = to;
}
}
int top[N], dfn[N], rk[N], t_cnt;
int n, m;
void dfs2(int u, int t) {
top[u] = t, dfn[u] = ++t_cnt, rk[t_cnt] = u;
if (son[u]) dfs2(son[u], t);
for (int i = head[u]; i; i = e[i].next) {
int to = e[i].to;
if (to == fa[u] || to == son[u]) continue;
dfs2(to, to);
}
}
void update(int u, int v) {
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(u, v);
modify(1, 1, n, dfn[top[u]], dfn[u], 1);
u = fa[top[u]];
}
if (dep[u] > dep[v]) swap(u, v);
if (u == v) return;
modify(1, 1, n, dfn[u] + 1, dfn[v], 1);
}
int ask(int u, int v) {
int sum = 0;
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(u, v);
sum += query(1, 1, n, dfn[top[u]], dfn[u]);
u = fa[top[u]];
}
if (dep[u] > dep[v]) swap(u, v);
if (u == v) return sum;
sum += query(1, 1, n, dfn[u] + 1, dfn[v]);
return sum;
}
void solve() {
cin >> n >> m;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
add(u, v), add(v, u);
}
dfs1(1, 0);
dfs2(1, 1);
char opt;
int x, y;
while (m--) {
cin >> opt >> x >> y;
if (opt == 'P') update(x, y);
else cout << ask(x, y) << '\n';
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
return 0;
}
标签:idx,int,sum,dep,dfn,P3038,USACO11DEC,Grass,top
From: https://www.cnblogs.com/Yuan-Jiawei/p/18437087