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
| #pragma GCC diagnostic error "-std=c++11" #include <bits/stdc++.h> using namespace std; const int MAXN = 500005; const int LOGN = 19; vector<int> edge[MAXN]; int father[MAXN][LOGN], size[MAXN]; long long f[MAXN][LOGN], ans, logn; char ch; inline void read(int &x) { x = 0; do ch = getchar(); while (!isdigit(ch)); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ '0'), ch = getchar(); } inline void dfs1(int u = 1) { for (register int i = 1; i < logn; i++) father[u][i] = father[father[u][i - 1]][i - 1]; size[u] = 1; for (auto i : edge[u]) if (i != father[u][0]) father[i][0] = u, dfs1(i), size[u] += size[i]; } inline void dfs2(int u = 1) { for (auto i : edge[u]) if (i != father[u][0]) dfs2(i); register long long sum = 1; for (register int i = 0; i < logn; i++) sum += f[u][i]; register int t = u; for (register int i = 0; i < logn; i++) sum -= f[u][i], ans -= sum * size[t], t = father[t][i], ans += sum * size[t], f[father[u][i]][i] += sum; } inline void addEdge(int u, int v) { edge[u].push_back(v); edge[v].push_back(u); } int n; int main() { read(n); logn = ceil(log2(n)); for (register int i = 1, u, v; i < n; i++) read(u), read(v), addEdge(u, v); father[1][0] = 1; dfs1(), dfs2(); cout << ans; return 0; }
|