WA20pts求助,悬赏一关
查看原帖
WA20pts求助,悬赏一关
550933
Tjaweiof楼主2024/3/22 09:06

RT

#include <bits/stdc++.h>
using namespace std;
const int N = 50000;
int n, fa[N + 1], dfn[N + 1], ddfn[N + 1], sz[N + 1], depth[N + 1], head[N + 1], son[N + 1], tot;
int t[N << 2], d[N << 2];
vector <int> e[N + 1];
void add(int x, long long v, int L, int R){
	t[x] += (R - L + 1) * v;
	d[x] += v;
	return;
}
void pushup(int x){
	t[x] = max(t[x << 1], t[x << 1 | 1]);
	return;
}
void pushdown(int x, int L, int R){
	if (!d[x]){
		return;
	}
	int mid = (L + R) >> 1;
	add(x << 1, d[x], L, mid);
	add(x << 1 | 1, d[x], mid + 1, R);
	d[x] = 0;
	return;
}
void change(int x, long long v, int l, int r, int L, int R){
	if (l == L && r == R){
		add(x, v, L, R);
		return;
	}
	pushdown(x, L, R);
	int mid = (L + R) >> 1;
	if (r <= mid){
		change(x << 1, v, l, r, L, mid);
	} else if (l > mid){
		change(x << 1 | 1, v, l, r, mid + 1, R);
	} else {
		change(x << 1, v, l, mid, L, mid);
		change(x << 1 | 1, v, mid + 1, r, mid + 1, R);
	}
	pushup(x);
	return;
}
void dfs(int x, int father, int dep){
	sz[x] = 1;
	depth[x] = dep;
	fa[x] = father;
	int maxn = 0, maxk = 0;
	for (auto u : e[x]){
		if (u != father){
			dfs(u, x, dep + 1);
			sz[x] += sz[u];
			if (sz[u] > maxn){
				maxn = sz[u];
				maxk = u;
			}
		}
	}
	son[x] = maxk;
	return;
}
void dfs2(int x, int he){
	tot++;
	dfn[x] = tot;
	ddfn[tot] = x;
	head[x] = he;
	if (son[x]){
		dfs2(son[x], he);
	}
	for (auto u : e[x]){
		if (u != fa[x] && u != son[x]){
			dfs2(u, u);
		}
	}
	return;
}
void change_path(int u, int v){
	while (head[u] != head[v]){
		if (depth[head[u]] < depth[head[v]]){
			swap(u, v);
		}
		change(1, 1, dfn[head[u]], dfn[u], 1, n);
		u = fa[head[u]];
	}
	if (depth[u] > depth[v]){
		swap(u, v);
	}
	change(1, 1, dfn[u], dfn[v], 1, n);
	return;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int k, u, v;
	cin >> n >> k;
	for (int i = 1; i < n; i++){
		cin >> u >> v;
		e[u].push_back(v);
		e[v].push_back(u);
	}
	dfs(1, 0, 1);
	dfs2(1, 1);
	while (k--){
		cin >> u >> v;
		change_path(u, v);
	}
	cout << t[1];
	return 0;
}
2024/3/22 09:06
加载中...