中文题意
给你个节点的一棵树,并且存在
次操作,每次操作把节点
之间路径上全部的点权值加一。问操作
次操作后整棵树最大的权值是多少?
Solution
读懂题的话,就是树上差分模板题,我实现的办法是树链剖分,会了之后就觉得比倍增快乐多了。给个OIWiki的差分链接
树上点差分就是:
#include <bits/stdc++.h> using namespace std; #define rep(i, sta, en) for(int i=sta; i<=en; ++i) #define repp(i, sta, en) for(int i=sta; i>=en; --i) typedef long long ll; typedef unsigned long long ull; typedef long double ld; inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar()) s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; } inline void print(ll x, int op = 10) { if (!x) { putchar('0'); if (op) putchar(op); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-'); int cnt = 0; while (tmp > 0) { F[cnt++] = tmp % 10 + '0'; tmp /= 10; } while (cnt > 0)putchar(F[--cnt]); if (op) putchar(op); } const int N = 5e4 + 7; int n, m; int fa[N], dep[N], sz[N], son[N], top[N]; vector<int> edge[N]; void dfs1(int u) { son[u] = -1; sz[u] = 1; for (auto& v : edge[u]) { if (dep[v]) continue; dep[v] = dep[u] + 1; fa[v] = u; dfs1(v); sz[u] += sz[v]; if (son[u] == -1 or sz[v] > sz[son[u]]) son[u] = v; } } void dfs2(int u, int t) { top[u] = t; if (son[u] == -1) return; dfs2(son[u], t); for (auto& v : edge[u]) if (v != son[u] and v != fa[u]) dfs2(v, v); } int lca(int u, int v) { while (top[u] != top[v]) { if (dep[top[u]] > dep[top[v]]) u = fa[top[u]]; else v = fa[top[v]]; } return dep[u] > dep[v] ? v : u; } int f[N], maxi; void dfs3(int u, int fa) { for (auto& v : edge[u]) { if (v == fa) continue; dfs3(v, u); f[u] += f[v]; } maxi = max(maxi, f[u]); } void solve() { n = read(), m = read(); rep(i, 2, n) { int u = read(), v = read(); edge[u].push_back(v); edge[v].push_back(u); } dep[1] = 1; dfs1(1); dfs2(1, 1); while (m--) { int u = read(), v = read(), tmp = lca(u, v); ++f[u], --f[tmp]; ++f[v], --f[fa[tmp]]; } dfs3(1, 0); print(maxi); } int main() { //int T = read(); rep(_, 1, T) { solve(); } return 0; }