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 80
| #include <cstdio> #include <vector> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } typedef long long LL; const int N = 1e5 + 10; vector <int> g[N]; int n, d[N], son[N]; LL ans, v[N << 2], *f[N], *h[N], *cur = v; void dfs1 (int x, int fa) { for (int i : g[x]) if (i ^ fa) { dfs1(i, x); (d[i] > d[son[x]]) && (son[x] = i); } d[x] = d[son[x]] + 1; } void dfs2 (int x, int fa) { if (son[x]) { f[son[x]] = f[x] + 1, h[son[x]] = h[x] - 1; dfs2(son[x], x); } f[x][0] = 1, ans += h[x][0]; for (int i : g[x]) if (i ^ fa && i ^ son[x]) { f[i] = cur, cur += d[i] << 1; h[i] = cur, cur += d[i]; dfs2(i, x); for (int k = 0; k < d[i]; k++) { k && (ans += f[x][k - 1] * h[i][k]); ans += h[x][k + 1] * f[i][k]; } for (int k = 0; k < d[i]; k++) { h[x][k + 1] += f[x][k + 1] * f[i][k]; k && (h[x][k - 1] += h[i][k]); f[x][k + 1] += f[i][k]; } } } int main () { read(n); for (int i = 1, a, b; i < n; i++) { read(a), read(b); g[a].push_back(b); g[b].push_back(a); } dfs1(1, 0); f[1] = cur, cur += d[1] << 1; h[1] = cur, cur += d[1]; dfs2(1, 0); write(ans); return 0; }
|