結果
| 問題 |
No.3348 Tree Balance
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-11-14 08:02:49 |
| 言語 | Nim (2.2.0) |
| 結果 |
AC
|
| 実行時間 | 2,063 ms / 5,000 ms |
| コード長 | 31,216 bytes |
| コンパイル時間 | 5,725 ms |
| コンパイル使用メモリ | 96,708 KB |
| 実行使用メモリ | 142,292 KB |
| 最終ジャッジ日時 | 2025-11-14 08:03:15 |
| 合計ジャッジ時間 | 23,271 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 25 |
ソースコード
import macros;macro ImportExpand(s:untyped):untyped = parseStmt($s[2])
# source: https://github.com/kemuniku/cplib/tree/main/src/cplib/tmpl/citrus.nim
ImportExpand "cplib/tmpl/citrus" <=== "when not declared CPLIB_TMPL_CITRUS:\n const CPLIB_TMPL_CITRUS* = 1\n {.warning[UnusedImport]: off.}\n {.hint[XDeclaredButNotUsed]: off.}\n import os\n import algorithm\n import sequtils\n import tables\n import macros\n import std/math\n import sets\n import strutils\n import strformat\n import sugar\n import streams\n import deques\n import bitops\n import heapqueue\n import options\n import hashes\n const MODINT998244353* = 998244353\n const MODINT1000000007* = 1000000007\n when not declared CPLIB_UTILS_CONSTANTS:\n const CPLIB_UTILS_CONSTANTS* = 1\n const INF32*: int32 = 1001000027.int32\n const INF64*: int = int(3300300300300300491)\n \n const INFL = INF64\n type double* = float64\n let readNext = iterator(getsChar: bool = false): string {.closure.} =\n while true:\n var si: string\n try: si = stdin.readLine\n except EOFError: yield \"\"\n for s in si.split:\n if getsChar:\n for i in 0..<s.len():\n yield s[i..i]\n else:\n if s.isEmptyOrWhitespace: continue\n yield s\n proc input*(t: typedesc[string]): string = readNext()\n proc input*(t: typedesc[char]): char = readNext(true)[0]\n proc input*(t: typedesc[int]): int = readNext().parseInt\n proc input*(t: typedesc[float]): float = readNext().parseFloat\n macro input*(t: typedesc, n: varargs[int]): untyped =\n var repStr = \"\"\n for arg in n:\n repStr &= &\"({arg.repr}).newSeqWith \"\n parseExpr(&\"{repStr}input({t})\")\n macro input*(ts: varargs[auto]): untyped =\n var tupStr = \"\"\n for t in ts:\n tupStr &= &\"input({t.repr}),\"\n parseExpr(&\"({tupStr})\")\n macro input*(n: int, ts: varargs[auto]): untyped =\n for typ in ts:\n if typ.typeKind != ntyAnything:\n error(\"Expected typedesc, got \" & typ.repr, typ)\n parseExpr(&\"({n.repr}).newSeqWith input({ts.repr})\")\n proc `fmtprint`*(x: int or string or char or bool): string = return $x\n proc `fmtprint`*(x: float or float32 or float64): string = return &\"{x:.16f}\"\n proc `fmtprint`*[T](x: seq[T] or Deque[T] or HashSet[T] or set[T]): string = return x.toSeq.join(\" \")\n proc `fmtprint`*[T, N](x: array[T, N]): string = return x.toSeq.join(\" \")\n proc `fmtprint`*[T](x: HeapQueue[T]): string =\n var q = x\n while q.len != 0:\n result &= &\"{q.pop()}\"\n if q.len != 0: result &= \" \"\n proc `fmtprint`*[T](x: CountTable[T]): string =\n result = x.pairs.toSeq.mapIt(&\"{it[0]}: {it[1]}\").join(\" \")\n proc `fmtprint`*[K, V](x: Table[K, V]): string =\n result = x.pairs.toSeq.mapIt(&\"{it[0]}: {it[1]}\").join(\" \")\n proc print*(prop: tuple[f: File, sepc: string, endc: string, flush: bool], args: varargs[string, `fmtprint`]) =\n for i in 0..<len(args):\n prop.f.write(&\"{args[i]}\")\n if i != len(args) - 1: prop.f.write(prop.sepc) else: prop.f.write(prop.endc)\n if prop.flush: prop.f.flushFile()\n proc print*(args: varargs[string, `fmtprint`]) = print((f: stdout, sepc: \" \", endc: \"\\n\", flush: false), args)\n const LOCAL_DEBUG{.booldefine.} = false\n macro getSymbolName(x: typed): string = x.toStrLit\n macro debug*(args: varargs[untyped]): untyped =\n when LOCAL_DEBUG:\n result = newNimNode(nnkStmtList, args)\n template prop(e: string = \"\"): untyped = (f: stderr, sepc: \"\", endc: e, flush: true)\n for i, arg in args:\n if arg.kind == nnkStrLit:\n result.add(quote do: print(prop(), \"\\\"\", `arg`, \"\\\"\"))\n else:\n result.add(quote do: print(prop(\": \"), getSymbolName(`arg`)))\n result.add(quote do: print(prop(), `arg`))\n if i != args.len - 1: result.add(quote do: print(prop(), \", \"))\n else: result.add(quote do: print(prop(), \"\\n\"))\n else:\n return (quote do: discard)\n proc `%`*(x: SomeInteger, y: SomeInteger): int =\n result = x mod y\n if y > 0 and result < 0: result += y\n if y < 0 and result > 0: result += y\n proc `//`*(x: SomeInteger, y: SomeInteger): int =\n result = x div y\n if y > 0 and result * y > x: result -= 1\n if y < 0 and result * y < x: result -= 1\n proc `^`*(x: SomeInteger, y: SomeInteger): int = x xor y\n proc `&`*(x: SomeInteger, y: SomeInteger): int = x and y\n proc `|`*(x: SomeInteger, y: SomeInteger): int = x or y\n proc `>>`*(x: SomeInteger, y: SomeInteger): int = x shr y\n proc `<<`*(x: SomeInteger, y: SomeInteger): int = x shl y\n proc `%=`*(x: var SomeInteger, y: SomeInteger): void = x = x % y\n proc `//=`*(x: var SomeInteger, y: SomeInteger): void = x = x // y\n proc `^=`*(x: var SomeInteger, y: SomeInteger): void = x = x ^ y\n proc `&=`*(x: var SomeInteger, y: SomeInteger): void = x = x & y\n proc `|=`*(x: var SomeInteger, y: SomeInteger): void = x = x | y\n proc `>>=`*(x: var SomeInteger, y: SomeInteger): void = x = x >> y\n proc `<<=`*(x: var SomeInteger, y: SomeInteger): void = x = x << y\n proc `[]`*(x, n: int): bool = (x and (1 shl n)) != 0\n proc `[]=`*(x: var int, n: int, i: bool) =\n if i: x = x or (1 << n)\n else: (if x[n]: x = x xor (1 << n))\n proc pow*(a, n: int, m = INF64): int =\n var\n rev = 1\n a = a\n n = n\n while n > 0:\n if n % 2 != 0: rev = (rev * a) mod m\n if n > 1: a = (a * a) mod m\n n >>= 1\n return rev\n when not declared CPLIB_MATH_ISQRT:\n const CPLIB_MATH_ISQRT* = 1\n proc isqrt*(n: int): int =\n var x = n\n var y = (x + 1) shr 1\n while y < x:\n x = y\n y = (x + n div x) shr 1\n return x\n \n proc chmax*[T](x: var T, y: T): bool {.discardable.} = (if x < y: (x = y; return true; ) return false)\n proc chmin*[T](x: var T, y: T): bool {.discardable.} = (if x > y: (x = y; return true; ) return false)\n proc `max=`*[T](x: var T, y: T) = x = max(x, y)\n proc `min=`*[T](x: var T, y: T) = x = min(x, y)\n proc at*(x: char, a = '0'): int = int(x) - int(a)\n proc Yes*(b: bool = true): void = print(if b: \"Yes\" else: \"No\")\n proc No*(b: bool = true): void = Yes(not b)\n proc YES_upper*(b: bool = true): void = print(if b: \"YES\" else: \"NO\")\n proc NO_upper*(b: bool = true): void = Yes_upper(not b)\n const DXY* = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n const DDXY* = [(1, -1), (1, 0), (1, 1), (0, -1), (0, 1), (-1, -1), (-1, 0), (-1, 1)]\n macro exit*(statement: untyped): untyped = (quote do: (`statement`; quit()))\n proc initHashSet[T](): Hashset[T] = initHashSet[T](0)\n"
# source: https://github.com/kemuniku/cplib/tree/main/src/cplib/graph/graph.nim
ImportExpand "cplib/graph/graph" <=== "when not declared CPLIB_GRAPH_GRAPH:\n const CPLIB_GRAPH_GRAPH* = 1\n\n import sequtils\n import math\n type DynamicGraph*[T] = ref object of RootObj\n edges*: seq[seq[(int32, T)]]\n len*: int\n type StaticGraph*[T] = ref object of RootObj\n src*, dst*: seq[int32]\n cost*: seq[T]\n elist*: seq[(int32, T)]\n start*: seq[int32]\n len*: int\n\n type WeightedDirectedGraph*[T] = ref object of DynamicGraph[T]\n type WeightedUnDirectedGraph*[T] = ref object of DynamicGraph[T]\n type UnWeightedDirectedGraph* = ref object of DynamicGraph[int]\n type UnWeightedUnDirectedGraph* = ref object of DynamicGraph[int]\n type WeightedDirectedStaticGraph*[T] = ref object of StaticGraph[T]\n type WeightedUnDirectedStaticGraph*[T] = ref object of StaticGraph[T]\n type UnWeightedDirectedStaticGraph* = ref object of StaticGraph[int]\n type UnWeightedUnDirectedStaticGraph* = ref object of StaticGraph[int]\n\n type GraphTypes*[T] = DynamicGraph[T] or StaticGraph[T]\n type DirectedGraph* = WeightedDirectedGraph or UnWeightedDirectedGraph or WeightedDirectedStaticGraph or UnWeightedDirectedStaticGraph\n type UnDirectedGraph* = WeightedUnDirectedGraph or UnWeightedUnDirectedGraph or WeightedUnDirectedStaticGraph or UnWeightedUnDirectedStaticGraph\n type WeightedGraph*[T] = WeightedDirectedGraph[T] or WeightedUnDirectedGraph[T] or WeightedDirectedStaticGraph[T] or WeightedUnDirectedStaticGraph[T]\n type UnWeightedGraph* = UnWeightedDirectedGraph or UnWeightedUnDirectedGraph or UnWeightedDirectedStaticGraph or UnWeightedUnDirectedStaticGraph\n type DynamicGraphTypes* = WeightedDirectedGraph or UnWeightedDirectedGraph or WeightedUnDirectedGraph or UnWeightedUnDirectedGraph\n type StaticGraphTypes* = WeightedDirectedStaticGraph or UnWeightedDirectedStaticGraph or WeightedUnDirectedStaticGraph or UnWeightedUnDirectedStaticGraph\n\n proc add_edge_dynamic_impl*[T](g: DynamicGraph[T], u, v: int, cost: T, directed: bool) =\n g.edges[u].add((v.int32, cost))\n if not directed: g.edges[v].add((u.int32, cost))\n\n proc initWeightedDirectedGraph*(N: int, edgetype: typedesc = int): WeightedDirectedGraph[edgetype] =\n result = WeightedDirectedGraph[edgetype](edges: newSeq[seq[(int32, edgetype)]](N), len: N)\n proc add_edge*[T](g: var WeightedDirectedGraph[T], u, v: int, cost: T) =\n g.add_edge_dynamic_impl(u, v, cost, true)\n\n proc initWeightedUnDirectedGraph*(N: int, edgetype: typedesc = int): WeightedUnDirectedGraph[edgetype] =\n result = WeightedUnDirectedGraph[edgetype](edges: newSeq[seq[(int32, edgetype)]](N), len: N)\n proc add_edge*[T](g: var WeightedUnDirectedGraph[T], u, v: int, cost: T) =\n g.add_edge_dynamic_impl(u, v, cost, false)\n\n proc initUnWeightedDirectedGraph*(N: int): UnWeightedDirectedGraph =\n result = UnWeightedDirectedGraph(edges: newSeq[seq[(int32, int)]](N), len: N)\n proc add_edge*(g: var UnWeightedDirectedGraph, u, v: int) =\n g.add_edge_dynamic_impl(u, v, 1, true)\n\n proc initUnWeightedUnDirectedGraph*(N: int): UnWeightedUnDirectedGraph =\n result = UnWeightedUnDirectedGraph(edges: newSeq[seq[(int32, int)]](N), len: N)\n proc add_edge*(g: var UnWeightedUnDirectedGraph, u, v: int) =\n g.add_edge_dynamic_impl(u, v, 1, false)\n\n proc len*[T](G: WeightedGraph[T]): int = G.len\n proc len*(G: UnWeightedGraph): int = G.len\n\n iterator `[]`*[T](g: WeightedDirectedGraph[T] or WeightedUnDirectedGraph[T], x: int): (int, T) =\n for e in g.edges[x]: yield (e[0].int, e[1])\n iterator `[]`*(g: UnWeightedDirectedGraph or UnWeightedUnDirectedGraph, x: int): int =\n for e in g.edges[x]: yield e[0].int\n\n proc add_edge_static_impl*[T](g: StaticGraph[T], u, v: int, cost: T, directed: bool) =\n g.src.add(u.int32)\n g.dst.add(v.int32)\n g.cost.add(cost)\n if not directed:\n g.src.add(v.int32)\n g.dst.add(u.int32)\n g.cost.add(cost)\n\n proc build_impl*[T](g: StaticGraph[T]) =\n g.start = newSeqWith(g.len + 1, 0.int32)\n for i in 0..<g.src.len:\n g.start[g.src[i]] += 1\n g.start.cumsum\n g.elist = newSeq[(int32, T)](g.start[^1])\n for i in countdown(g.src.len - 1, 0):\n var u = g.src[i]\n var v = g.dst[i]\n g.start[u] -= 1\n g.elist[g.start[u]] = (v, g.cost[i])\n proc build*(g: StaticGraphTypes) = g.build_impl()\n\n proc initWeightedDirectedStaticGraph*(N: int, edgetype: typedesc = int, capacity: int = 0): WeightedDirectedStaticGraph[edgetype] =\n result = WeightedDirectedStaticGraph[edgetype](\n src: newSeqOfCap[int32](capacity),\n dst: newSeqOfCap[int32](capacity),\n cost: newSeqOfCap[edgetype](capacity),\n elist: newSeq[(int32, edgetype)](0),\n start: newSeq[int32](0),\n len: N\n )\n proc add_edge*[T](g: var WeightedDirectedStaticGraph[T], u, v: int, cost: T) =\n g.add_edge_static_impl(u, v, cost, true)\n\n proc initWeightedUnDirectedStaticGraph*(N: int, edgetype: typedesc = int, capacity: int = 0): WeightedUnDirectedStaticGraph[edgetype] =\n result = WeightedUnDirectedStaticGraph[edgetype](\n src: newSeqOfCap[int32](capacity*2),\n dst: newSeqOfCap[int32](capacity*2),\n cost: newSeqOfCap[edgetype](capacity*2),\n elist: newSeq[(int32, edgetype)](0),\n start: newSeq[int32](0),\n len: N\n )\n proc add_edge*[T](g: var WeightedUnDirectedStaticGraph[T], u, v: int, cost: T) =\n g.add_edge_static_impl(u, v, cost, false)\n\n proc initUnWeightedDirectedStaticGraph*(N: int, capacity: int = 0): UnWeightedDirectedStaticGraph =\n result = UnWeightedDirectedStaticGraph(\n src: newSeqOfCap[int32](capacity),\n dst: newSeqOfCap[int32](capacity),\n cost: newSeqOfCap[int](capacity),\n elist: newSeq[(int32, int)](0),\n start: newSeq[int32](0),\n len: N\n )\n proc add_edge*(g: var UnWeightedDirectedStaticGraph, u, v: int) =\n g.add_edge_static_impl(u, v, 1, true)\n\n proc initUnWeightedUnDirectedStaticGraph*(N: int, capacity: int = 0): UnWeightedUnDirectedStaticGraph =\n result = UnWeightedUnDirectedStaticGraph(\n src: newSeqOfCap[int32](capacity*2),\n dst: newSeqOfCap[int32](capacity*2),\n cost: newSeqOfCap[int](capacity*2),\n elist: newSeq[(int32, int)](0),\n start: newSeq[int32](0),\n len: N\n )\n proc add_edge*(g: var UnWeightedUnDirectedStaticGraph, u, v: int) =\n g.add_edge_static_impl(u, v, 1, false)\n\n proc static_graph_initialized_check*[T](g: StaticGraph[T]) = assert g.start.len > 0, \"Static Graph must be initialized before use.\"\n\n iterator `[]`*[T](g: WeightedDirectedStaticGraph[T] or WeightedUnDirectedStaticGraph[T], x: int): (int, T) =\n g.static_graph_initialized_check()\n for i in g.start[x]..<g.start[x+1]: yield (g.elist[i][0].int, g.elist[i][1])\n iterator `[]`*(g: UnWeightedDirectedStaticGraph or UnWeightedUnDirectedStaticGraph, x: int): int =\n g.static_graph_initialized_check()\n for i in g.start[x]..<g.start[x+1]: yield g.elist[i][0].int\n\n iterator to_and_cost*[T](g: DynamicGraph[T], x: int): (int, T) =\n for e in g.edges[x]: yield (e[0].int, e[1])\n iterator to_and_cost*[T](g: StaticGraph[T], x: int): (int, T) =\n g.static_graph_initialized_check()\n for i in g.start[x]..<g.start[x+1]: yield (g.elist[i][0].int, g.elist[i][1])\n \n import tables\n\n type UnWeightedUnDirectedTableGraph*[T] = object \n toi* : Table[T,int]\n v* : seq[T]\n graph* : UnWeightedUnDirectedGraph\n\n type UnWeightedDirectedTableGraph*[T] = object \n toi* : Table[T,int]\n v* : seq[T]\n graph* : UnWeightedDirectedGraph\n\n type WeightedUnDirectedTableGraph*[T,S] = object \n toi* : Table[T,int]\n v* : seq[T]\n graph* : WeightedUnDirectedGraph[S]\n\n type WeightedDirectedTableGraph*[T,S] = object \n toi* : Table[T,int]\n v* : seq[T]\n graph* : WeightedDirectedGraph[S]\n\n type UnWeightedTableGraph*[T] = UnWeightedUnDirectedTableGraph[T] or UnWeightedDirectedTableGraph[T]\n type WeightedTableGraph*[T,S] = WeightedUnDirectedTableGraph[T,S] or WeightedDirectedTableGraph[T,S]\n\n proc initUnWeightedUnDirectedTableGraph*[T](V:seq[T]):UnWeightedUnDirectedTableGraph[T]=\n for i in 0..<len(V):\n result.toi[V[i]] = i\n result.graph = initUnWeightedUnDirectedGraph(len(V))\n result.v = V\n\n proc initUnWeightedDirectedTableGraph*[T](V:seq[T]):UnWeightedDirectedTableGraph[T]=\n for i in 0..<len(V):\n result.toi[V[i]] = i\n result.graph = initUnWeightedDirectedGraph(len(V))\n result.v = V\n\n proc initWeightedUnDirectedTableGraph*[T](V:seq[T],S:typedesc = int):WeightedUnDirectedTableGraph[T,S]=\n for i in 0..<len(V):\n result.toi[V[i]] = i\n result.graph = initWeightedUnDirectedGraph(len(V),S)\n result.v = V\n\n proc initWeightedDirectedTableGraph*[T](V:seq[T],S:typedesc = int):WeightedDirectedTableGraph[T,S]=\n for i in 0..<len(V):\n result.toi[V[i]] = i\n result.graph = initWeightedDirectedGraph(len(V),S)\n result.v = V\n\n proc add_edge*[T](g: var UnWeightedTableGraph[T],u,v:int)=\n g.graph.add_edge(g.toi[u],g.toi[v])\n\n proc add_edge*[T,S](g: var WeightedTableGraph[T,S],u,v:int,cost:S)=\n g.graph.add_edge(g.toi[u],g.toi[v],cost)\n\n iterator `[]`*[T,S](g: WeightedDirectedTableGraph[T,S] or WeightedUnDirectedTableGraph[T,S], x: T): (T, S) = \n for (x,y) in g.graph[g.toi[x]]:\n yield (g.v[x],y)\n iterator `[]`*[T](g: UnWeightedDirectedTableGraph[T] or UnWeightedUnDirectedTableGraph[T], x: T): T = \n for x in g.graph[g.toi[x]]:\n yield g.v[x]\n\n"
# source: https://github.com/kemuniku/cplib/tree/main/src/cplib/collections/avlset.nim
ImportExpand "cplib/collections/avlset" <=== "when not declared CPLIB_COLLECTIONS_AVLSET:\n const CPLIB_COLLECTIONS_AVLSET* = 1\n when not declared CPLIB_COLLECTIONS_AVLTREE:\n const CPLIB_COLLECTIONS_AVLTREE* = 1\n # 以下をNimに移植\n # https://nachiavivias.github.io/cp-library/cpp/array/bbst-list.html\n type AvlTreeNode*[K] = ref object\n l*, r*, p*: AvlTreeNode[K]\n h*, len*: int\n key*: K\n proc update[K](node: AvlTreeNode[K]) =\n node.h = 0\n node.len = 1\n if not node.l.isNil:\n if node.l.h + 1 > node.h: node.h = node.l.h + 1\n node.len += node.l.len\n if not node.r.isNil:\n if node.r.h + 1 > node.h: node.h = node.r.h + 1\n node.len += node.r.len\n proc set_children[K](node, l, r: AvlTreeNode[K]) =\n node.l = l\n if not l.isNil: l.p = node\n node.r = r\n if not r.isNil: r.p = node\n node.update()\n proc rebalance[K](node: AvlTreeNode[K]): AvlTreeNode[K] =\n var node = node\n var l = node.l\n var r = node.r\n var lh = if not l.isNil: l.h else: 0\n var rh = if not r.isNil: r.h else: 0\n if lh + 1 < rh:\n var rl = r.l\n var rr = r.r\n var rlh = if not rl.isNil: rl.h else: 0\n var rrh = if not rr.isNil: rr.h else: 0\n if rlh <= rrh:\n r.p = node.p\n node.set_children(l, rl)\n r.set_children(node, rr)\n return r\n else:\n rl.p = node.p\n node.set_children(l, rl.l)\n r.set_children(rl.r, rr)\n rl.set_children(node, r)\n return rl\n elif rh + 1 < lh:\n var ll = l.l\n var lr = l.r\n var llh = if not ll.isNil: ll.h else: 0\n var lrh = if not lr.isNil: lr.h else: 0\n if lrh <= llh:\n l.p = node.p\n node.set_children(lr, r)\n l.set_children(ll, node)\n return l\n else:\n lr.p = node.p\n node.set_children(lr.r, r)\n l.set_children(ll, lr.l)\n lr.set_children(l, node)\n return lr\n node.update\n return node\n proc rebalance_to_root[K](node: AvlTreeNode[K]): AvlTreeNode[K] =\n var node = node\n while not node.p.isNil:\n var cp = node.p\n if cp.l == node: cp.l = node.rebalance\n else: cp.r = node.rebalance\n node = cp\n return node.rebalance\n proc rootOf*[K](node: AvlTreeNode[K]): AvlTreeNode[K] =\n result = node\n while not result.p.isNil: result = result.p\n proc node_search[K](node: AvlTreeNode[K], key: K, strict: bool): (AvlTreeNode[K], AvlTreeNode[K]) =\n var node = node\n var result_l: AvlTreeNode[K] = nil\n var result_r: AvlTreeNode[K] = nil\n while not node.isNil:\n if (strict and key < node.key) or (not strict and key <= node.key):\n result_r = node\n node = node.l\n else:\n result_l = node\n node = node.r\n return (result_l, result_r)\n proc lower_bound_node*[K](node: AvlTreeNode[K], key: K): (AvlTreeNode[K], AvlTreeNode[K]) = node_search[K](node, key, false)\n proc upper_bound_node*[K](node: AvlTreeNode[K], key: K): (AvlTreeNode[K], AvlTreeNode[K]) = node_search[K](node, key, true)\n proc insert*[K](node, x: AvlTreeNode[K]): AvlTreeNode[K] =\n if node.isNil: return x\n var (ql, qr) = node.lower_bound_node(x.key)\n if not ql.isNil and ql.r.isNil:\n ql.set_children(ql.l, x)\n return ql.rebalance_to_root\n qr.set_children(x, qr.r)\n return qr.rebalance_to_root\n proc erase*[K](node, x, nxt: AvlTreeNode[K]): AvlTreeNode[K] =\n var xp = x.p\n if x.r.isNil:\n var xl = x.l\n if not xl.isNil: xl.p = xp\n if not xp.isNil:\n if xp.l == x: xp.l = xl\n else: xp.r = xl\n if xp.isNil: result = xl\n else: result = xp.rebalance_to_root\n else:\n var nxtp = nxt.p\n var nxtr = nxt.r\n if not xp.isNil:\n if xp.l == x: xp.l = nxt\n else: xp.r = nxt\n nxt.p = xp\n nxt.l = x.l\n if not nxt.l.isNil: nxt.l.p = nxt\n if x.r == nxt:\n nxt.update\n result = nxt.rebalance_to_root\n else:\n if nxtp.l == nxt: nxtp.l = nxtr\n else: nxtp.r = nxtr\n if not nxtr.isNil: nxtr.p = nxtp\n nxt.r = x.r\n nxt.r.p = nxt\n nxt.update\n result = nxtp.rebalance_to_root\n x.l = nil\n x.r = nil\n x.p = nil\n x.update\n proc next*[K](node: AvlTreeNode[K]): AvlTreeNode[K] =\n var node = node\n if not node.r.isNil:\n node = node.r\n while not node.l.isNil: node = node.l\n return node\n while not node.p.isNil and node.p.r == node: node = node.p\n return node.p\n proc prev*[K](node: AvlTreeNode[K]): AvlTreeNode[K] =\n var node = node\n if not node.l.isNil:\n node = node.l\n while not node.r.isNil: node = node.r\n return node\n while not node.p.isNil and node.p.l == node: node = node.p\n return node.p\n proc get*[K](node: AvlTreeNode[K], idx: int): AvlTreeNode[K] =\n assert idx >= 0\n if idx >= node.len: return nil\n result = node\n var idx = idx\n while (result.l.isNil and idx != 0) or (not result.l.isNil and result.l.len != idx):\n if result.l.isNil or result.l.len < idx:\n idx -= (if result.l.isNil: 1 else: result.l.len + 1)\n assert(not result.r.isNil)\n result = result.r\n else:\n result = result.l\n proc index*[K](node: AvlTreeNode[K]): int =\n var node = node\n if node.isNil: return 0\n result = (if node.l.isNil: 0 else: node.l.len)\n while not node.p.isNil:\n if node.p.r == node:\n if node.p.l.isNil: result += 1\n else: result += node.p.l.len + 1\n node = node.p\n \n import options\n import sequtils\n import strutils\n\n type AvlSortedMultiSet*[T] = object\n root*: AvlTreeNode[T]\n\n type AVLSortedSet*[T] = object\n root*: AvlTreeNode[T]\n\n type AVLSets[T] = AvlSortedMultiSet[T] or AVLSortedSet[T]\n\n proc len*[T](self: AVLSets[T]): int = (if self.root.isNil: 0 else: self.root.len)\n proc lowerBound*[T](self: AVLSets[T], x: T): int =\n var (ql, qr) = self.root.lower_bound_node(x)\n if qr.isNil: return self.len\n return qr.index\n proc index*[T](self: AVLSets[T], x: T): int = self.lowerBound(x)\n proc upperBound*[T](self: AVLSets[T], x: T): int =\n var (ql, qr) = self.root.upper_bound_node(x)\n if qr.isNil: return self.len\n return qr.index\n proc index_right*[T](self: AVLSets[T], x: T): int = self.upperBound(x)\n proc count*[T](self: AVLSets[T], x: T): int = self.upperBound(x) - self.lowerBound(x)\n proc newnode[T](x: T): AvlTreeNode[T] =\n return AvlTreeNode[T](len: 1, h: 1, key: x)\n proc lt*[T](self: AVLSets[T], x: T): Option[T] =\n var (node, _) = self.root.lower_bound_node(x)\n if node.isNil: return none(T)\n return some(node.key)\n proc le*[T](self: AVLSets[T], x: T): Option[T] =\n var (node, _) = self.root.upper_bound_node(x)\n if node.isNil: return none(T)\n return some(node.key)\n proc gt*[T](self: AVLSets[T], x: T): Option[T] =\n var (_, node) = self.root.upper_bound_node(x)\n if node.isNil: return none(T)\n return some(node.key)\n proc ge*[T](self: AVLSets[T], x: T): Option[T] =\n var (_, node) = self.root.lower_bound_node(x)\n if node.isNil: return none(T)\n return some(node.key)\n proc contains*[T](self: AVLSets[T], x: T): bool =\n var (_, node) = self.root.lower_bound_node(x)\n return not node.isNil and node.key == x\n proc incl*[T](self: var AVLSortedMultiSet[T], x: T) =\n var node = newnode(x)\n self.root = self.root.insert(node)\n proc incl*[T](self: var AVLSortedSet[T], x: T): bool {.discardable.} =\n if self.contains(x): return false\n var node = newnode(x)\n self.root = self.root.insert(node)\n return true\n proc excl*[T](self: var AVLSets[T], x: T): bool {.discardable.} =\n if x notin self: return false\n var (_, node) = self.root.lower_bound_node(x)\n self.root = self.root.erase(node, node.next)\n return true\n proc `[]`*[T](self: AVLSets[T], idx: int): T =\n assert idx < self.root.len\n return self.root.get(idx).key\n proc `[]`*[T](self: AVLSets[T], idx: BackwardsIndex): T =\n var idx = self.len - int(idx)\n return self[idx]\n proc pop*[T](self: var AVLSets[T], idx: int = -1): T =\n var idx = idx\n if idx < 0: idx = self.len + idx\n assert idx < self.root.len\n var node = self.root.get(idx)\n result = node.key\n self.root = self.root.erase(node, node.next)\n iterator items*[T](self: AVLSets[T]): T =\n if not self.root.isNil:\n var stack = @[(0, self.root)]\n while stack.len > 0:\n var (t, node) = stack.pop\n if t == 0:\n stack.add((1, node))\n if not node.l.isNil: stack.add((0, node.l))\n elif t == 1:\n yield node.key\n if not node.r.isNil: stack.add((0, node.r))\n proc `$`*[T](self: AVLSets[T]): string = self.toSeq.join(\" \")\n proc initAvlSortedMultiSet*[T](v: seq[T] = @[]): AvlSortedMultiSet[T] =\n result = AvlSortedMultiSet[T]()\n for item in v: result.incl(item)\n proc initAvlSortedSet*[T](v: seq[T] = @[]): AvlSortedSet[T] =\n result = AvlSortedSet[T]()\n for item in v: result.incl(item)\n"
# {.checks: off.}
# 適当に根をとって根付き木として考える。
# 選ばれた2辺の位置関係は、互いに祖先ー子孫の関係にある/ないのいずれかである
# 選ぶ辺を一つ決めて、以下の2パターンを試すと良さそう
# ①自身の子孫の部分木のうち、ちょうど半分に近い部分木を一つ選ぶ
# ②自身の子孫ではない部分木であって、残っている重みの半分に近い部分木を一つ選ぶ
# ②の「自身の子孫ではない部分木」は真面目にやると少し面倒だが
# 「DFSで自身よりも後に走査される部分木」と言い換えると比較的簡単に取得できそう
var n = input(int)
var w = input(int, n)
var wsum = w.sum
var ans = INFL
var g = initUnWeightedUnDirectedStaticGraph(n)
for _ in 0..<n-1:
var u,v = input(int) - 1
g.add_edge(u, v)
g.build
var sts = newSeqWith(n, initAvlSortedMultiSet[int]())
var t = newSeq[int](n)
proc dfs1(u, par: int): int =
var total = w[u]
for v in g[u]:
if v == par: continue
total += dfs1(v, u)
if sts[u].len < sts[v].len:
swap(sts[u], sts[v])
for x in sts[v]:
sts[u].incl(x)
sts[u].incl(total)
var p = sts[u].upperBound(total // 2)
if par != -1:
if p in 0..<sts[u].len:
var mn = min(@[sts[u][p], total - sts[u][p], wsum - total])
var mx = max(@[sts[u][p], total - sts[u][p], wsum - total])
ans.min= mx - mn
if p-1 in 0..<sts[u].len:
var mn = min(@[sts[u][p-1], total - sts[u][p-1], wsum - total])
var mx = max(@[sts[u][p-1], total - sts[u][p-1], wsum - total])
ans.min= mx - mn
t[u] = total
return total
var rt = 0
discard dfs1(rt, -1)
var st = sts[rt]
proc dfs2(u, par: int): int =
st.excl(t[u])
var total = w[u]
for v in g[u]:
if v == par: continue
total += dfs2(v, u)
# st.excl(total)
var p = st.upperBound((wsum - total) // 2)
if par != -1:
if p in 0..<st.len:
var mn = min(@[st[p], total, wsum - total - st[p]])
var mx = max(@[st[p], total, wsum - total - st[p]])
ans.min= mx - mn
if p-1 in 0..<st.len:
var mn = min(@[st[p-1], total, wsum - total - st[p-1]])
var mx = max(@[st[p-1], total, wsum - total - st[p-1]])
ans.min= mx - mn
return total
discard dfs2(rt, -1)
print(ans)