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
|
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #define LL long long #define MAXN (100000) #define lowbit(i) ((i) & (-(i))) using namespace std; struct node { int size, fa, depth; LL sumsd, sumsd2; } a[MAXN + 5]; struct edg { int from, to, next; } b[MAXN * 2 + 5]; int g[MAXN + 5], cntb, n; LL ans[MAXN + 5]; void ade(int fr, int t) { b[++cntb] = {fr, t, g[fr]}; g[fr] = cntb; } void init(int now) { a[now].size = 1; a[now].sumsd = a[now].depth; a[now].sumsd2 = (LL)a[now].depth * a[now].depth; for (int i = g[now]; i; i = b[i].next) if (b[i].to != a[now].fa) { a[b[i].to].fa = now; a[b[i].to].depth = a[now].depth + 1; init(b[i].to); a[now].size += a[b[i].to].size; a[now].sumsd += a[b[i].to].sumsd; a[now].sumsd2 += a[b[i].to].sumsd2; } } void dfs(int now, LL nows, LL nowf) { if (now != 1) { nows = a[now].sumsd - (a[now].depth - 2) * a[now].size; nowf += a[a[now].fa].sumsd - a[now].sumsd - (a[a[now].fa].depth - 1) * (a[a[now].fa].size - a[now].size) + n - a[a[now].fa].size; ans[now] = ans[a[now].fa] + a[now].size - 2 * nows + a[1].size - a[now].size + 2 * nowf; } for (int i = g[now]; i; i = b[i].next) if (b[i].to != a[now].fa) dfs(b[i].to, nows, nowf); } int main() { scanf("%d", &n); for (int i = 1, xi, yi; i < n; i++) scanf("%d%d", &xi, &yi), ade(xi + 1, yi + 1), ade(yi + 1, xi + 1); a[1].depth = 1; init(1); ans[1] = a[1].sumsd2; dfs(1, a[1].sumsd, 0); for (int i = 1; i <= n; i++) printf("%lld\n", ans[i]); return 0; }
|