2020 wannafly camp day1 E tree and path - a tree difference

Topic links: point I ah ╭ (╯ ^ ╰) ╮

Subject to the effect:

    Rooted tree, find a number of weights and path
    weights of a path is defined as:
    from the start to the end of the shortest path, the number of edges go up × × number of edges go down

Problem-solving ideas:

    For one path ( in , v ) (U, v) , set the length of l e n only , l c a lca to in in distance of x x
     a n s l c a = x ( l e n x ) ans_{lca} = x * (len - x) , set up l c a lca direction in in son of direction s O n son
     a n s s O n = ( x 1 ) ( l e n x + 1 ) ans_ {its} = (x - 1) * (len - x + 1)
     a n s l c a a n s s O n = l e n 2 x + 1 lca ans_ {} - {ans_ its} = len - 2x + 1

    for l e n + 1 Only + 1 this part, the right is equivalent to all points on this path + = l e n + 1 + = Only + 1
    For 2 x -2x this section can also be treated by the difference:
    Point in in of x x is 1 1 , whose father 2 2 , followed by 4... 4...
    That is the difference processing arithmetic sequence of thought

Core: a tree difference processing arithmetic sequence

#include<bits/stdc++.h>
#define rint register int
#define x first
#define y second
#define deb(x) cerr<<#x<<" = "<<(x)<<'\n';
using namespace std;
typedef long long ll;
using pii = pair <ll,ll>;
const int maxn = 3e5 + 5;
int n, m, f[maxn][35];
ll ans[maxn], dep[maxn];
vector <int> g[maxn];
pii a[maxn];

void dfs1(int u, int fa, int de) {
	dep[u] = de, f[u][0] = fa;
	for(int i=1; i<=30; i++)
		f[u][i] = f[f[u][i-1]][i-1];
	for(auto v : g[u]) {
		if(v == fa) continue;
		dfs1(v, u, de+1);
	}
}

int LCA(int x, int y){
	if(dep[x]<dep[y]) swap(x, y);
	for(int i=30; i>=0; i--)
		if(dep[f[x][i]]>=dep[y])
			x = f[x][i];
	if(x == y) return x;
	for(int i=30; i>=0; i--)
		if(f[x][i] ^ f[y][i])
			x=f[x][i], y=f[y][i];
	return f[x][0];
}

void dfs2(int u, int fa) {
	for(auto v : g[u]) {
		if(v == fa) continue;
		dfs2(v, u);
		a[u].x += a[v].x;
		a[u].y += a[v].y;
	}
	a[u].x -= 2ll * a[u].y;
}

void dfs3(int u, int fa, ll num) {
	ans[u] = num;
	for(auto v : g[u]) {
		if(v == fa) continue;
		dfs3(v, u, num - a[v].x);
	}
}

int main() {
	scanf("%d%d", &n, &m);
	for(int i=1, u, v; i<n; i++) {
		scanf("%d%d", &u, &v);
		g[u].push_back(v);
		g[v].push_back(u);
	}
	dfs1(1, 0, 1);
	while(m--) {
		ll u, v, lca, len;
		scanf("%lld%lld", &u, &v);
		lca = LCA(u, v);
		len = dep[u] + dep[v] - 2ll * dep[lca];
		a[u].x += len + 1, a[u].y += 1;
		a[lca].x -= len + 1 - 2ll * (dep[u] - dep[lca]), a[lca].y -= 1;

		a[v].x += len + 1, a[v].y += 1;
		a[lca].x -= len + 1 - 2ll * (dep[v] - dep[lca]), a[lca].y -= 1;
		ans[1] += 1ll * (dep[u] - dep[lca]) * (dep[v] - dep[lca]);
	}
	dfs2(1, 0);
	dfs3(1, 0, ans[1]);
	for(int i=1; i<=n; i++) printf("%lld\n", ans[i]);
}
Published 221 original articles · won praise 220 · views 20000 +

Guess you like

Origin blog.csdn.net/Scar_Halo/article/details/104095579