洛谷P3128 [USACO15DEC]最大流Max Flow(树上差分)

题意

题目链接

Sol

树上差分模板题

发现自己傻傻的分不清边差分和点差分

边差分就是对边进行操作,我们在\(u, v\)除加上\(val\),同时在\(lca\)处减去\(2 * val\)

点差分是对点操作,我们在\(u, v\)处加上\(val\),在\(lca\)\(fa[lca]\)处减去\(val\)

就本题而言,属于点差分

#include<bits/stdc++.h>
const int MAXN = 1e5 + 10;
using namespace std;
inline int read() {
	char c = getchar(); int x = 0, f = 1;
	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;
}
int N, K, dep[MAXN], fa[MAXN][21], dfn[MAXN], val[MAXN], tot;
vector<int> v[MAXN];
void dfs(int x, int _fa) {
	fa[x][0] = _fa; dep[x] = dep[fa[x][0]] + 1; dfn[++tot] = x;
	for(int i = 1; i <= 20; i++) fa[x][i] = fa[fa[x][i - 1]][i - 1];
	for(int i = 0, to; i < v[x].size(); i++) {
		if((to = v[x][i]) == _fa) continue;
		dfs(to, x);
	}
}
int LCA(int x, int y) {
	if(dep[x] < dep[y]) swap(x, y);
	for(int i = 20; i >= 0; i--) if(dep[fa[x][i]] >= dep[y]) x = fa[x][i];
	if(x == y) return x;
	for(int i = 20; i >= 0; i--) if(fa[x][i] ^ fa[y][i]) x = fa[x][i], y = fa[y][i];
	return fa[x][0];
}
int main() {
	N = read(); K = read();
	for(int i = 1; i <= N - 1; i++) {
		int x = read(), y = read();
		v[x].push_back(y); v[y].push_back(x);
	}
	dfs(1, 0);
	for(int i = 1; i <= K; i++) {
		int x = read(), y = read();
		val[x]++; val[y]++;
		int lca = LCA(x, y); 
		val[lca]--; val[fa[lca][0]]--;
	}
	int ans = 0;
	for(int i = N; i >= 1; i--) val[fa[dfn[i]][0]] += val[dfn[i]];
	for(int i = 1; i <= N; i++) ans = max(ans, val[i]);
	printf("%d", ans);
	return 0;
}
posted @ 2018-09-27 21:09  自为风月马前卒  阅读(302)  评论(0编辑  收藏  举报

Contact with me