トピックリンク:ポイント私はああ╭(╯^╰)╮
効果の件名:
ルート付きツリー、重みとパスの数を見つける
パスの重みは次のように定義される。
開始から最短パスの最後に、エッジの数が上がります
エッジの数が下ります
問題解決のアイデア:
1つのパス
、の長さを設定します
、
に
の距離
の設定、
方向
方向の息子
以下のために
この部分、右側はこのパス上の全ての点に相当します
の場合
、このセクションはまた違いによって治療することができる:
ポイント
の
あります
、父親
、続いて
すなわち、思考の算術シーケンスを処理の差であります
コア:算術シーケンスを処理ツリー差
#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]);
}