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
| #include <bits/stdc++.h> #define fi first #define se second using namespace std; using pii = pair<int, int>; using ll = long long; const int N = 1e5 + 5; int n, sz[N]; vector<pii> G[N]; ll dp[N][2]; void dfs(int u, int fa) { sz[u] = 1; for(auto it : G[u]) { int v = it.fi, w = it.se; if(v==fa) continue; dfs(v, u); sz[u] += sz[v]; dp[u][0] += dp[v][0] + w*sz[v]; } } void dfs2(int u, int fa) { for(auto it : G[u]) { int v = it.fi, w = it.se; if(v==fa) continue; dp[v][1] = dp[u][0] - dp[v][0] - w*sz[v] + w*(sz[u] - sz[v]) + dp[u][1] + w*(n - sz[u]); dfs2(v, u); } } void print(__int128 x) { static int buf[70], tp; tp = 0; if(!x) buf[tp = 1] = 0; while(x) { buf[++tp] = x%10; x /= 10; } for(int i=tp; i>=1; i--) printf("%d", buf[i]); } void solve(int kase) { scanf("%d", &n); for(int i=1; i<=n; i++) G[i].clear(), dp[i][0] = dp[i][1] = 0; for(int i=1; i<n; i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); G[u].emplace_back(v, w); G[v].emplace_back(u, w); } dfs(1, 0); dfs2(1, 0); vector<ll> alldis(n, 0); for(int i=1; i<=n; i++) alldis[i-1] = dp[i][0] + dp[i][1]; sort(begin(alldis), end(alldis)); reverse(begin(alldis), end(alldis)); __int128 ans = 0; for(int i=1; i<n; i++) ans += (__int128)i*alldis[i]; printf("Case #%d: ", kase); print(ans); puts(""); } int main() { int _; scanf("%d", &_); for(int kase=1; kase<=_; ++kase) solve(kase); return 0; }
|