import strutils, sequtils type Edge = tuple[to: int, d: int] var ans: int64 = 0 dp: seq[int64] size: seq[int] proc dfs(g: seq[seq[Edge]], i: int, p: int) = if dp[i] >= 0: return dp[i] = 0 for e in g[i]: if e.to == p: continue dfs(g, e.to, i) size[i] += size[e.to] dp[i] += dp[e.to] + size[e.to] * e.d ans += dp[i] proc sfd(g: seq[seq[Edge]], i: int, p: int, acc: int64) = for e in g[i]: if e.to == p: continue let nxt_acc = acc + (dp[i] - dp[e.to] - size[e.to] * e.d) + (size[0] - size[e.to]) * e.d sfd(g, e.to, i, nxt_acc) ans += nxt_acc proc main() = let n = stdin.readLine.parseInt var g = newSeqWith(n, newSeq[Edge]()) for i in 1..