【洛谷】P3128 [USACO15DEC] Max Flow P 的题解
题解
谔谔,LCA + + + 树上差分,差点就被难倒了 qaq
今天就是 CSP 初赛了,祝大家也祝我自己 rp++!!!
其实是一道树上差分的板子题,先建树,对于一条路径 w ( u , v ) w(u,v) w(u,v),将其权值 + 1 +1 +1,然后再将它们的 LCA 和 LCA 的父亲各减去 1 1 1(LCA 用倍增比较方便),最后用 DFS 遍历整棵树统计和即可。
代码
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'),x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
struct node {
int to, next;
} edge[500005];
int fa[50005][30], head[500005], power[50005], depth[50005], lg[50005];
int n, k, ans = 0, tot = 0;
void add(int x, int y) {
edge[++ tot].to = y;
edge[tot].next = head[x];
head[x] = tot;
}
void dfs(int now, int father) {
fa[now][0] = father;
depth[now] = depth[father] + 1;
for(int i = 1; i <= lg[depth[now]]; ++i)
fa[now][i] = fa[fa[now][i - 1]][i - 1];
for(int i = head[now]; i; i = edge[i].next)
if (edge[i].to != father) dfs(edge[i].to, now);
}
int LCA(int x, int y) {
if(depth[x] < depth[y]) swap(x, y);
while(depth[x] > depth[y]) x = fa[x][lg[depth[x] - depth[y]] - 1];
if(x == y) return x;
for(int k = lg[depth[x]] - 1; k >= 0; k --) {
if(fa[x][k] != fa[y][k]) x = fa[x][k], y = fa[y][k];
}
return fa[x][0];
}
void find(int u, int father) {
for(int i = head[u]; i; i = edge[i].next) {
int to = edge[i].to;
if(to == father) continue;
find(to, u);
power[u] += power[to];
}
ans = max(ans, power[u]);
}
int main() {
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
n = read(), k = read();
int x, y;
for(int i = 1; i <= n; i ++) {
lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
}
for(int i = 1; i <= n - 1; i ++) {
x = read(), y = read();
add(x, y);
add(y, x);
}
dfs(1, 0);
int s, t;
for(int i = 1; i <= k; i ++) {
s = read(), t = read();
int ancestor = LCA(s, t);
power[s] ++;
power[t] ++;
power[ancestor] --;
power[fa[ancestor][0]] --;
}
find(1, 0);
write(ans);
return 0;
}
标签:lg,洛谷,USACO15DEC,power,int,题解,fa,depth,read
From: https://blog.csdn.net/ZH_qaq/article/details/142394406