1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include <bits/stdc++.h> using namespace std; using LL = long long; #define FOR(i, x, y) for (decay<decltype(y)>::type i = (x), _##i = (y); i < _##i; ++i) #define FORD(i, x, y) for (decay<decltype(x)>::type i = (x), _##i = (y); i > _##i; --i) #ifdef zerol #define dbg(args...) do { cout << "\033[32;1m" << #args << " -> "; err(args); } while (0) #else #define dbg(...) #endif void err() { cout << "\033[39;0m" << endl; } template<template<typename...> class T, typename t, typename... Args> void err(T<t> a, Args... args) { for (auto x: a) cout << x << ' '; err(args...); } template<typename T, typename... Args> void err(T a, Args... args) { cout << a << ' '; err(args...); } // ----------------------------------------------------------------------------- const int maxn = 1E5 + 100; vector<int> G[maxn]; int n, fa[maxn], son[maxn], sd[maxn]; LL ans, T;
void predfs(int u) { sd[u] = 0; int& maxs = son[u] = -1; for (int v: G[u]) { if (v == fa[u]) continue; fa[v] = u; predfs(v); sd[u] = max(sd[u], sd[v]); if (maxs == -1 || sd[v] > sd[maxs]) maxs = v; } sd[u] += 1; }
void mod(deque<LL>& f, deque<LL>& g) { f.push_front(0); if (!g.empty()) g.pop_front(); }
void dfs(int u, deque<LL>& f, deque<LL>& g) { if (son[u] == -1) { f.push_back(1); return; } dfs(son[u], f, g); mod(f, g); f.resize(sd[u]); g.resize(sd[u]); f[0]++; ans += g[0]; deque<LL> ff, gg; for (int v: G[u]) if (v != son[u] && v != fa[u]) { ff.clear(); gg.clear(); dfs(v, ff, gg); mod(ff, gg); FOR (i, 0, ff.size()) ans += ff[i] * g[i]; FOR (i, 0, gg.size()) ans += gg[i] * f[i]; FOR (i, 0, gg.size()) g[i] += gg[i]; FOR (i, 0, ff.size()) g[i] += f[i] * ff[i]; FOR (i, 0, ff.size()) f[i] += ff[i]; } }
int main() { #ifdef zerol freopen("in", "r", stdin); #endif cin >> T; while (T--) { cin >> n; FOR (i, 1, n + 1) G[i].clear(); FOR (_, 1, n) { int u, v; scanf("%d%d", &u, &v); G[u].push_back(v); G[v].push_back(u); } predfs(1); ans = 0; deque<LL> t, tt; dfs(1, t, tt); cout << ans << endl; } }
|