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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include <bits/stdc++.h>
#define x first #define y second #define y1 Y1 #define y2 Y2 #define mp make_pair #define pb push_back
using namespace std;
typedef long long LL; typedef pair<int, int> pii;
template <typename T> inline int Chkmax (T &a, T b) { return a < b ? a = b, 1 : 0; } template <typename T> inline int Chkmin (T &a, T b) { return a > b ? a = b, 1 : 0; }
inline void proc_status() { ifstream t ("/proc/self/status"); cerr << string (istreambuf_iterator <char> (t), istreambuf_iterator <char> ()) <<endl; }
template <typename T> T read () { T sum = 0, fl = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') fl = -1; for (; isdigit(ch); ch = getchar()) sum = (sum << 3) + (sum << 1) + ch - '0'; return sum * fl; }
const int Maxn = 1e5 + 100;
int N, e, Begin[Maxn], To[Maxn << 1], Next[Maxn << 1];
inline void add_edge (int x, int y) { To[++e] = y; Next[e] = Begin[x]; Begin[x] = e; }
LL Pool[Maxn << 2]; LL *f[Maxn], *g[Maxn], *now(Pool + 1), ans; int dep[Maxn], maxdep[Maxn], son[Maxn];
inline void new_node (int x) { f[x] = now, now += ((maxdep[x] - dep[x] + 1) << 1); g[x] = now, now += ((maxdep[x] - dep[x] + 1) << 1); }
inline void dfs_pre (int x, int fa) { maxdep[x] = dep[x] = dep[fa] + 1; for (int i = Begin[x]; i; i = Next[i]) { int y = To[i]; if (y == fa) continue; dfs_pre (y, x); Chkmax(maxdep[x], maxdep[y]); if (maxdep[y] > maxdep[son[x]]) son[x] = y; } }
inline void dfs (int x, int fa) { if (son[x]) { f[son[x]] = f[x] + 1, g[son[x]] = g[x] - 1; dfs(son[x], x); } f[x][0] = 1, ans += g[x][0]; for (int i = Begin[x]; i; i = Next[i]) { int y = To[i]; if (y == fa || y == son[x]) continue; new_node(y); dfs(y, x); for (int j = 1; j <= maxdep[y] - dep[x]; ++j) ans += 1ll * f[y][j - 1] * g[x][j] + 1ll * f[x][j - 1] * g[y][j]; for (int j = 0; j <= maxdep[y] - dep[x]; ++j) { if (j) f[x][j] += f[y][j - 1]; if (j) g[x][j - 1] += g[y][j]; g[x][j + 1] += 1ll * f[x][j + 1] * f[y][j]; } } }
inline void Solve () { ans = 0; dfs_pre(1, 0); new_node(1); dfs(1, 0); cout<<ans<<endl; }
inline void Input () { for (int i = 1; i < N; ++i) { int x = read<int>(), y = read<int>(); add_edge (x, y), add_edge (y, x); } }
inline void Init () { e = 0; memset(Begin, 0, sizeof Begin); memset(son, 0, sizeof son); while (now != Pool) *now = 0, --now; *now = 0; now = Pool + 1; }
int main() { #ifndef ONLINE_JUDGE freopen("three.in", "r", stdin); freopen("three.out", "w", stdout); #endif while (scanf("%d", &N) != EOF) { if (!N) break; Init(); Input(); Solve(); } return 0; }
|