做題記錄 Luogu P3478
阿新 • • 發佈:2021-06-20
Luogu P3478 [POI2008]STA-Station
換根 DP 模板題
邊目錄要開雙倍空間
不是 DAG 圖要連雙向邊!!!
#include<bits/stdc++.h> using namespace std; #define ll long long #define N 2000005 ll first[N], Next[N], to[N], size[N], f[N], tot, n; void add(ll x, ll y) { Next[++tot] = first[x]; first[x] = tot; to[tot] = y; return; } void dfs_lenth(ll u, ll fa, ll dep) { size[u] = 1; f[1] += dep; for(ll i = first[u]; i; i = Next[i]) { ll v = to[i]; if(v == fa) { continue; } dfs_lenth(v, u, dep + 1); size[u] += size[v]; } return; } void dp(ll u, ll fa) { for(ll i = first[u]; i; i = Next[i]) { ll v = to[i]; if(v == fa) { continue; } f[v] = f[u] + n - 2 * size[v]; dp(v, u); } return; } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; ll u, v; for(ll i = 1; i < n; i++) { cin >> u >> v; add(u, v); add(v, u); } dfs_lenth(1, 0, 0); dp(1, 0); ll ans = 1; for(ll i = 2; i <= n; i++) { ans = (f[ans] < f[i] ? i : ans); } cout << ans; return 0; }