結果

問題 No.3442 Good Vertex Connectivity
コンテスト
ユーザー kemuniku
提出日時 2026-02-06 23:45:41
言語 Nim
(2.2.6)
結果
WA  
実行時間 -
コード長 40,693 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 6,882 ms
コンパイル使用メモリ 87,840 KB
実行使用メモリ 53,628 KB
最終ジャッジ日時 2026-02-06 23:47:24
合計ジャッジ時間 94,550 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 8 WA * 61
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

# source: src/cplib/utils/constants.nim
when not declared CPLIB_UTILS_CONSTANTS:
    const CPLIB_UTILS_CONSTANTS* = 1
    const INF32*: int32 = 1001000027.int32
    const INF64*: int = int(3300300300300300491)

# source: src/cplib/tmpl/sheep.nim
when not declared CPLIB_TMPL_SHEEP:
    const CPLIB_TMPL_SHEEP* = 1
    {.warning[UnusedImport]: off.}
    {.hint[XDeclaredButNotUsed]: off.}
    import algorithm
    import sequtils
    import tables
    import macros
    import math
    import sets
    import strutils
    import strformat
    import sugar
    import heapqueue
    import streams
    import deques
    import bitops
    import std/lenientops
    import options
    #入力系
    proc scanf(formatstr: cstring){.header: "<stdio.h>", varargs.}
    proc getchar(): char {.importc: "getchar_unlocked", header: "<stdio.h>", discardable.}
    proc ii(): int {.inline.} = scanf("%lld\n", addr result)
    proc lii(N: int): seq[int] {.inline.} = newSeqWith(N, ii())
    proc si(): string {.inline.} =
        result = ""
        var c: char
        while true:
            c = getchar()
            if c == ' ' or c == '\n' or c == '\255':
                break
            result &= c
    #chmin,chmax
    template `max=`(x, y) = x = max(x, y)
    template `min=`(x, y) = x = min(x, y)
    proc chmin[T](x: var T, y: T):bool=
        if x > y:
            x = y
            return true
        return false
    proc chmax[T](x: var T, y: T):bool=
        if x < y:
            x = y
            return true
        return false
    #bit演算
    proc `%`*(x: int, y: int): int =
        result = x mod y
        if y > 0 and result < 0: result += y
        if y < 0 and result > 0: result += y
    proc `//`*(x: int, y: int): int{.inline.} =
        result = x div y
        if y > 0 and result * y > x: result -= 1
        if y < 0 and result * y < x: result -= 1
    proc `%=`(x: var int, y: int): void = x = x%y
    proc `//=`(x: var int, y: int): void = x = x//y
    proc `**`(x: int, y: int): int = x^y
    proc `**=`(x: var int, y: int): void = x = x^y
    proc `^`(x: int, y: int): int = x xor y
    proc `|`(x: int, y: int): int = x or y
    proc `&`(x: int, y: int): int = x and y
    proc `>>`(x: int, y: int): int = x shr y
    proc `<<`(x: int, y: int): int = x shl y
    proc `~`(x: int): int = not x
    proc `^=`(x: var int, y: int): void = x = x ^ y
    proc `&=`(x: var int, y: int): void = x = x & y
    proc `|=`(x: var int, y: int): void = x = x | y
    proc `>>=`(x: var int, y: int): void = x = x >> y
    proc `<<=`(x: var int, y: int): void = x = x << y
    proc `[]`(x: int, n: int): bool = (x and (1 shl n)) != 0
    #便利な変換
    proc `!`(x: char, a = '0'): int = int(x)-int(a)
    #定数
    const INF = INF64
    #converter

    #range
    iterator range(start: int, ends: int, step: int): int =
        var i = start
        if step < 0:
            while i > ends:
                yield i
                i += step
        elif step > 0:
            while i < ends:
                yield i
                i += step
    iterator range(ends: int): int = (for i in 0..<ends: yield i)
    iterator range(start: int, ends: int): int = (for i in
            start..<ends: yield i)

    #joinが非stringでめちゃくちゃ遅いやつのパッチ
    proc join*[T: not string](a: openArray[T], sep: string = ""): string = a.mapit($it).join(sep)

    proc dump[T](arr:seq[seq[T]])=
        for i in 0..<len(arr):
            echo arr[i]

    proc sum(slice:HSlice[int,int]):int=
        return (slice.a+slice.b)*len(slice)//2
    
    proc `<`[T](l,r:seq[T]):bool=
        for i in 0..<min(len(l),len(r)):
            if l[i] > r[i]:
                return false
            elif l[i] < r[i]:
                return true
        return len(l) < len(r)
# source: src/cplib/graph/graph.nim
when not declared CPLIB_GRAPH_GRAPH:
    const CPLIB_GRAPH_GRAPH* = 1

    import sequtils
    import math
    type DynamicGraph*[T] = ref object of RootObj
        edges*: seq[seq[(int32, T)]]
        len*: int
    type StaticGraph*[T] = ref object of RootObj
        src*, dst*: seq[int32]
        cost*: seq[T]
        elist*: seq[(int32, T)]
        start*: seq[int32]
        len*: int

    type WeightedDirectedGraph*[T] = ref object of DynamicGraph[T]
    type WeightedUnDirectedGraph*[T] = ref object of DynamicGraph[T]
    type UnWeightedDirectedGraph* = ref object of DynamicGraph[int]
    type UnWeightedUnDirectedGraph* = ref object of DynamicGraph[int]
    type WeightedDirectedStaticGraph*[T] = ref object of StaticGraph[T]
    type WeightedUnDirectedStaticGraph*[T] = ref object of StaticGraph[T]
    type UnWeightedDirectedStaticGraph* = ref object of StaticGraph[int]
    type UnWeightedUnDirectedStaticGraph* = ref object of StaticGraph[int]

    type GraphTypes*[T] = DynamicGraph[T] or StaticGraph[T]
    type DirectedGraph* = WeightedDirectedGraph or UnWeightedDirectedGraph or WeightedDirectedStaticGraph or UnWeightedDirectedStaticGraph
    type UnDirectedGraph* = WeightedUnDirectedGraph or UnWeightedUnDirectedGraph or WeightedUnDirectedStaticGraph or UnWeightedUnDirectedStaticGraph
    type WeightedGraph*[T] = WeightedDirectedGraph[T] or WeightedUnDirectedGraph[T] or WeightedDirectedStaticGraph[T] or WeightedUnDirectedStaticGraph[T]
    type UnWeightedGraph* = UnWeightedDirectedGraph or UnWeightedUnDirectedGraph or UnWeightedDirectedStaticGraph or UnWeightedUnDirectedStaticGraph
    type DynamicGraphTypes* = WeightedDirectedGraph or UnWeightedDirectedGraph or WeightedUnDirectedGraph or UnWeightedUnDirectedGraph
    type StaticGraphTypes* = WeightedDirectedStaticGraph or UnWeightedDirectedStaticGraph or WeightedUnDirectedStaticGraph or UnWeightedUnDirectedStaticGraph

    proc add_edge_dynamic_impl*[T](g: DynamicGraph[T], u, v: int, cost: T, directed: bool) =
        g.edges[u].add((v.int32, cost))
        if not directed: g.edges[v].add((u.int32, cost))

    proc initWeightedDirectedGraph*(N: int, edgetype: typedesc = int): WeightedDirectedGraph[edgetype] =
        result = WeightedDirectedGraph[edgetype](edges: newSeq[seq[(int32, edgetype)]](N), len: N)
    proc add_edge*[T](g: var WeightedDirectedGraph[T], u, v: int, cost: T) =
        g.add_edge_dynamic_impl(u, v, cost, true)

    proc initWeightedUnDirectedGraph*(N: int, edgetype: typedesc = int): WeightedUnDirectedGraph[edgetype] =
        result = WeightedUnDirectedGraph[edgetype](edges: newSeq[seq[(int32, edgetype)]](N), len: N)
    proc add_edge*[T](g: var WeightedUnDirectedGraph[T], u, v: int, cost: T) =
        g.add_edge_dynamic_impl(u, v, cost, false)

    proc initUnWeightedDirectedGraph*(N: int): UnWeightedDirectedGraph =
        result = UnWeightedDirectedGraph(edges: newSeq[seq[(int32, int)]](N), len: N)
    proc add_edge*(g: var UnWeightedDirectedGraph, u, v: int) =
        g.add_edge_dynamic_impl(u, v, 1, true)

    proc initUnWeightedUnDirectedGraph*(N: int): UnWeightedUnDirectedGraph =
        result = UnWeightedUnDirectedGraph(edges: newSeq[seq[(int32, int)]](N), len: N)
    proc add_edge*(g: var UnWeightedUnDirectedGraph, u, v: int) =
        g.add_edge_dynamic_impl(u, v, 1, false)

    proc len*[T](G: WeightedGraph[T]): int = G.len
    proc len*(G: UnWeightedGraph): int = G.len

    iterator `[]`*[T](g: WeightedDirectedGraph[T] or WeightedUnDirectedGraph[T], x: int): (int, T) =
        for e in g.edges[x]: yield (e[0].int, e[1])
    iterator `[]`*(g: UnWeightedDirectedGraph or UnWeightedUnDirectedGraph, x: int): int =
        for e in g.edges[x]: yield e[0].int

    proc add_edge_static_impl*[T](g: StaticGraph[T], u, v: int, cost: T, directed: bool) =
        g.src.add(u.int32)
        g.dst.add(v.int32)
        g.cost.add(cost)
        if not directed:
            g.src.add(v.int32)
            g.dst.add(u.int32)
            g.cost.add(cost)

    proc build_impl*[T](g: StaticGraph[T]) =
        g.start = newSeqWith(g.len + 1, 0.int32)
        for i in 0..<g.src.len:
            g.start[g.src[i]] += 1
        g.start.cumsum
        g.elist = newSeq[(int32, T)](g.start[^1])
        for i in countdown(g.src.len - 1, 0):
            var u = g.src[i]
            var v = g.dst[i]
            g.start[u] -= 1
            g.elist[g.start[u]] = (v, g.cost[i])
    proc build*(g: StaticGraphTypes) = g.build_impl()

    proc initWeightedDirectedStaticGraph*(N: int, edgetype: typedesc = int, capacity: int = 0): WeightedDirectedStaticGraph[edgetype] =
        result = WeightedDirectedStaticGraph[edgetype](
            src: newSeqOfCap[int32](capacity),
            dst: newSeqOfCap[int32](capacity),
            cost: newSeqOfCap[edgetype](capacity),
            elist: newSeq[(int32, edgetype)](0),
            start: newSeq[int32](0),
            len: N
        )
    proc add_edge*[T](g: var WeightedDirectedStaticGraph[T], u, v: int, cost: T) =
        g.add_edge_static_impl(u, v, cost, true)

    proc initWeightedUnDirectedStaticGraph*(N: int, edgetype: typedesc = int, capacity: int = 0): WeightedUnDirectedStaticGraph[edgetype] =
        result = WeightedUnDirectedStaticGraph[edgetype](
            src: newSeqOfCap[int32](capacity*2),
            dst: newSeqOfCap[int32](capacity*2),
            cost: newSeqOfCap[edgetype](capacity*2),
            elist: newSeq[(int32, edgetype)](0),
            start: newSeq[int32](0),
            len: N
        )
    proc add_edge*[T](g: var WeightedUnDirectedStaticGraph[T], u, v: int, cost: T) =
        g.add_edge_static_impl(u, v, cost, false)

    proc initUnWeightedDirectedStaticGraph*(N: int, capacity: int = 0): UnWeightedDirectedStaticGraph =
        result = UnWeightedDirectedStaticGraph(
            src: newSeqOfCap[int32](capacity),
            dst: newSeqOfCap[int32](capacity),
            cost: newSeqOfCap[int](capacity),
            elist: newSeq[(int32, int)](0),
            start: newSeq[int32](0),
            len: N
        )
    proc add_edge*(g: var UnWeightedDirectedStaticGraph, u, v: int) =
        g.add_edge_static_impl(u, v, 1, true)

    proc initUnWeightedUnDirectedStaticGraph*(N: int, capacity: int = 0): UnWeightedUnDirectedStaticGraph =
        result = UnWeightedUnDirectedStaticGraph(
            src: newSeqOfCap[int32](capacity*2),
            dst: newSeqOfCap[int32](capacity*2),
            cost: newSeqOfCap[int](capacity*2),
            elist: newSeq[(int32, int)](0),
            start: newSeq[int32](0),
            len: N
        )
    proc add_edge*(g: var UnWeightedUnDirectedStaticGraph, u, v: int) =
        g.add_edge_static_impl(u, v, 1, false)

    proc static_graph_initialized_check*[T](g: StaticGraph[T]) = assert g.start.len > 0, "Static Graph must be initialized before use."

    iterator `[]`*[T](g: WeightedDirectedStaticGraph[T] or WeightedUnDirectedStaticGraph[T], x: int): (int, T) =
        g.static_graph_initialized_check()
        for i in g.start[x]..<g.start[x+1]: yield (g.elist[i][0].int, g.elist[i][1])
    iterator `[]`*(g: UnWeightedDirectedStaticGraph or UnWeightedUnDirectedStaticGraph, x: int): int =
        g.static_graph_initialized_check()
        for i in g.start[x]..<g.start[x+1]: yield g.elist[i][0].int

    iterator to_and_cost*[T](g: DynamicGraph[T], x: int): (int, T) =
        for e in g.edges[x]: yield (e[0].int, e[1])
    iterator to_and_cost*[T](g: StaticGraph[T], x: int): (int, T) =
        g.static_graph_initialized_check()
        for i in g.start[x]..<g.start[x+1]: yield (g.elist[i][0].int, g.elist[i][1])
    
    import tables

    type UnWeightedUnDirectedTableGraph*[T] = object 
        toi* : Table[T,int]
        v* : seq[T]
        graph* : UnWeightedUnDirectedGraph

    type UnWeightedDirectedTableGraph*[T] = object 
        toi* : Table[T,int]
        v* : seq[T]
        graph* : UnWeightedDirectedGraph

    type WeightedUnDirectedTableGraph*[T,S] = object 
        toi* : Table[T,int]
        v* : seq[T]
        graph* : WeightedUnDirectedGraph[S]

    type WeightedDirectedTableGraph*[T,S] = object 
        toi* : Table[T,int]
        v* : seq[T]
        graph* : WeightedDirectedGraph[S]

    type UnWeightedTableGraph*[T] = UnWeightedUnDirectedTableGraph[T] or UnWeightedDirectedTableGraph[T]
    type WeightedTableGraph*[T,S] = WeightedUnDirectedTableGraph[T,S] or WeightedDirectedTableGraph[T,S]

    proc initUnWeightedUnDirectedTableGraph*[T](V:seq[T]):UnWeightedUnDirectedTableGraph[T]=
        for i in 0..<len(V):
            result.toi[V[i]] = i
        result.graph = initUnWeightedUnDirectedGraph(len(V))
        result.v = V

    proc initUnWeightedDirectedTableGraph*[T](V:seq[T]):UnWeightedDirectedTableGraph[T]=
        for i in 0..<len(V):
            result.toi[V[i]] = i
        result.graph = initUnWeightedDirectedGraph(len(V))
        result.v = V

    proc initWeightedUnDirectedTableGraph*[T](V:seq[T],S:typedesc = int):WeightedUnDirectedTableGraph[T,S]=
        for i in 0..<len(V):
            result.toi[V[i]] = i
        result.graph = initWeightedUnDirectedGraph(len(V),S)
        result.v = V

    proc initWeightedDirectedTableGraph*[T](V:seq[T],S:typedesc = int):WeightedDirectedTableGraph[T,S]=
        for i in 0..<len(V):
            result.toi[V[i]] = i
        result.graph = initWeightedDirectedGraph(len(V),S)
        result.v = V

    proc add_edge*[T](g: var UnWeightedTableGraph[T],u,v:int)=
        g.graph.add_edge(g.toi[u],g.toi[v])

    proc add_edge*[T,S](g: var WeightedTableGraph[T,S],u,v:int,cost:S)=
        g.graph.add_edge(g.toi[u],g.toi[v],cost)

    iterator `[]`*[T,S](g: WeightedDirectedTableGraph[T,S] or WeightedUnDirectedTableGraph[T,S], x: T): (T, S) = 
        for (x,y) in g.graph[g.toi[x]]:
            yield (g.v[x],y)
    iterator `[]`*[T](g: UnWeightedDirectedTableGraph[T] or UnWeightedUnDirectedTableGraph[T], x: T): T = 
        for x in g.graph[g.toi[x]]:
            yield g.v[x]


# source: src/cplib/tree/heavylightdecomposition.nim
when not declared CPLIB_TREE_HLD:
    const CPLIB_TREE_HLD* = 1
    import sequtils
    import algorithm
    import sets
    # https://atcoder.jp/contests/abc337/submissions/50216964
    # ↑上記の提出より引用
    type HeavyLightDecomposition* = ref object 
        N*: int
        P*, PP*, PD*, D*, I*, rangeL*, rangeR*: seq[int]
    proc initHld*(g: UnDirectedGraph, root: int): HeavyLightDecomposition =
        var hld = HeavyLightDecomposition()
        var n: int = g.len
        hld.N = n
        hld.P = newSeqWith(n, -1)
        hld.I = newSeqWith(n, 0)
        hld.I[0] = root
        var iI = 1
        for i in 0..<n:
            var p = hld.I[i]
            for e in g[p]:
                if hld.P[p] != e:
                    hld.I[iI] = e
                    hld.P[e] = p
                    iI += 1
        var Z = newSeqWith(n, 1)
        var nx = newSeqWith(n, -1)
        hld.PP = newSeqWith(n, 0)
        for i in 0..<n:
            hld.PP[i] = i
        for i in 1..<n:
            var p = hld.I[n-i]
            Z[hld.P[p]] += Z[p]
            if nx[hld.P[p]] == -1 or Z[nx[hld.P[p]]] < Z[p]:
                nx[hld.P[p]] = p
        for p in hld.I:
            if nx[p] != -1:
                hld.PP[nx[p]] = p
        hld.PD = newSeqWith(n, n)
        hld.PD[root] = 0
        hld.D = newSeqWith(n, 0)
        for p in hld.I:
            if p != root:
                hld.PP[p] = hld.PP[hld.PP[p]]
                hld.PD[p] = min(hld.PD[hld.PP[p]], hld.PD[hld.P[p]]+1)
                hld.D[p] = hld.D[hld.P[p]]+1
        hld.rangeL = newSeqWith(n, 0)
        hld.rangeR = newSeqWith(n, 0)
        for p in hld.I:
            hld.rangeR[p] = hld.rangeL[p] + Z[p]
            var ir = hld.rangeR[p]
            for e in g[p]:
                if hld.P[p] != e and e != nx[p]:
                    ir -= Z[e]
                    hld.rangeL[e] = ir
            if nx[p] != -1:
                hld.rangeL[nx[p]] = hld.rangeL[p] + 1
        for i in 0..<n:
            hld.I[hld.rangeL[i]] = i
        return hld
    proc initHld*(g: DirectedGraph, root: int): HeavyLightDecomposition =
        var n = g.len
        var gn = initUnWeightedUnDirectedStaticGraph(n)
        var seen = initHashSet[(int, int)]()
        for i in 0..<n:
            for (j, _) in g[i]:
                if (i, j) notin seen:
                    gn.add_edge(i, j)
                    seen.incl((i, j))
                    seen.incl((j, i))
        gn.build
        return initHld(gn, root)
    proc initHld*(adj: seq[seq[int]], root: int): HeavyLightDecomposition =
        var n = adj.len
        var gn = initUnWeightedUnDirectedStaticGraph(n)
        var seen = initHashSet[(int, int)]()
        for i in 0..<n:
            for j in adj[i]:
                if (i, j) notin seen:
                    gn.add_edge(i, j)
                    seen.incl((i, j))
                    seen.incl((j, i))
        gn.build
        return initHld(gn, root)
    proc numVertices*(hld: HeavyLightDecomposition): int = hld.N
    proc depth*(hld: HeavyLightDecomposition, p: int): int = hld.D[p]
    proc toSeq*(hld: HeavyLightDecomposition, vtx: int): int = hld.rangeL[vtx]
    proc toVtx*(hld: HeavyLightDecomposition, seqidx: int): int = hld.I[seqidx]
    proc toSeq2In*(hld: HeavyLightDecomposition, vtx: int): int = hld.rangeL[vtx] * 2 - hld.D[vtx]
    proc toSeq2Out*(hld: HeavyLightDecomposition, vtx: int): int = hld.rangeR[vtx] * 2 - hld.D[vtx] - 1
    proc parentOf*(hld: HeavyLightDecomposition, v: int): int = hld.P[v]
    proc heavyRootOf*(hld: HeavyLightDecomposition, v: int): int = hld.PP[v]
    proc heavyChildOf*(hld: HeavyLightDecomposition, v: int): int =
        if hld.toSeq(v) == hld.N-1:
            return -1
        var cand = hld.toVtx(hld.toSeq(v) + 1)
        if hld.PP[v] == hld.PP[cand]:
            return cand
        -1
    proc lca*(hld: HeavyLightDecomposition, u: int, v: int): int =
        var (u, v) = (u, v)
        if hld.PD[u] < hld.PD[v]:
            swap(u, v)
        while hld.PD[u] > hld.PD[v]:
            u = hld.P[hld.PP[u]]
        while hld.PP[u] != hld.PP[v]:
            u = hld.P[hld.PP[u]]
            v = hld.P[hld.PP[v]]
        if hld.D[u] > hld.D[v]:
            return v
        u
    proc dist*(hld: HeavyLightDecomposition, u: int, v: int): int =
        hld.depth(u) + hld.depth(v) - hld.depth(hld.lca(u, v)) * 2
    proc path*(hld: HeavyLightDecomposition, r: int, c: int, include_root: bool, reverse_path: bool): seq[(int, int)] =
        var (r, c) = (r, c)
        var k = hld.PD[c] - hld.PD[r] + 1
        if k <= 0:
            return @[]
        var res = newSeqWith(k, (0, 0))
        for i in 0..<k-1:
            res[i] = (hld.rangeL[hld.PP[c]], hld.rangeL[c] + 1)
            c = hld.P[hld.PP[c]]
        if hld.PP[r] != hld.PP[c] or hld.D[r] > hld.D[c]:
            return @[]
        var root_off = int(not include_root)
        res[^1] = (hld.rangeL[r]+root_off, hld.rangeL[c]+1)
        if res[^1][0] == res[^1][1]:
            discard res.pop()
            k -= 1
        if reverse_path:
            for i in 0..<k:
                res[i] = (hld.N - res[i][1], hld.N - res[i][0])
        else:
            res.reverse()
        res
    proc subtree*(hld: HeavyLightDecomposition, p: int): (int, int) = (hld.rangeL[p], hld.rangeR[p])
    iterator subtreeV*(hld: HeavyLightDecomposition, p: int):int=
        for i in hld.rangeL[p]..<hld.rangeR[p]:
            yield hld.toVtx(i)
    proc median*(hld: HeavyLightDecomposition, x: int, y: int, z: int): int =
        hld.lca(x, y) xor hld.lca(y, z) xor hld.lca(x, z)
    proc la*(hld: HeavyLightDecomposition, starting: int, goal: int, d: int): int =
        var (u, v, d) = (starting, goal, d)
        if d < 0:
            return -1
        var g = hld.lca(u, v)
        var dist0 = hld.D[u] - hld.D[g] * 2 + hld.D[v]
        if dist0 < d:
            return -1
        var p = u
        if hld.D[u] - hld.D[g] < d:
            p = v
            d = dist0 - d
        while hld.D[p] - hld.D[hld.PP[p]] < d:
            d -= hld.D[p] - hld.D[hld.PP[p]] + 1
            p = hld.P[hld.PP[p]]
        hld.I[hld.rangeL[p] - d]
    iterator children*(hld: HeavyLightDecomposition, v: int): int =
        var s = hld.rangeL[v] + 1
        while s < hld.rangeR[v]:
            var w = hld.toVtx(s)
            yield w
            s += hld.rangeR[w] - hld.rangeL[w]
    

    proc initAuxiliaryTree*(hld:HeavyLightDecomposition,v:seq[int]):UnWeightedUnDirectedTableGraph[int]=
        var v = v.sortedByit(hld.toseq(it))
        for i in 0..<(len(v)-1):
            v.add(hld.lca(v[i],v[i+1]))
        v = v.sortedByIt(hld.toseq(it)).deduplicate(true)
        var stack :seq[int]
        result = initUnWeightedUnDirectedTableGraph[int](v)
        stack.add(v[0])
        
        for i in 1..<len(v):
            while len(stack) > 0 and hld.toSeq2Out(stack[^1]) < hld.toseq2In(v[i]):
                discard stack.pop()
            if len(stack) != 0:
                result.add_edge(stack[^1],v[i])
            stack.add(v[i])
    
    proc initAuxiliaryWeightedTree*(hld:HeavyLightDecomposition,v:seq[int]):WeightedUnDirectedTableGraph[int,int]=
        var v = v.sortedByit(hld.toseq(it))
        for i in 0..<(len(v)-1):
            v.add(hld.lca(v[i],v[i+1]))
        v = v.sortedByIt(hld.toseq(it)).deduplicate(true)
        var stack :seq[int]
        result = initWeightedUnDirectedTableGraph(v,int)
        stack.add(v[0])
        for i in 1..<len(v):
            while len(stack) > 0 and hld.toSeq2Out(stack[^1]) < hld.toseq2In(v[i]):
                discard stack.pop()
            if len(stack) != 0:
                result.add_edge(stack[^1],v[i],hld.depth(v[i])-hld.depth(stack[^1]))
            stack.add(v[i])


# source: src/atcoder/internal_bit.nim
when not declared ATCODER_INTERNAL_BITOP_HPP:
    const ATCODER_INTERNAL_BITOP_HPP* = 1
    import std/bitops
  
  #ifdef _MSC_VER
  #include <intrin.h>
  #endif
  
  # @param n `0 <= n`
  # @return minimum non-negative `x` s.t. `n <= 2**x`
    proc ceil_pow2*(n:SomeInteger):int =
      var x = 0
      while (1.uint shl x) < n.uint: x.inc
      return x
  # @param n `1 <= n`
  # @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`
    proc bsf*(n:SomeInteger):int =
      return countTrailingZeroBits(n)
  
# source: src/atcoder/rangeutils.nim
when not declared ATCODER_RANGEUTILS_HPP:
    const ATCODER_RANGEUTILS_HPP* = 1
    type RangeType* = Slice[int] | HSlice[int, BackwardsIndex] | Slice[BackwardsIndex]
    type IndexType* = int | BackwardsIndex
    template halfOpenEndpoints*(p:Slice[int]):(int,int) = (p.a, p.b + 1)
    template `^^`*(s, i: untyped): untyped =
      (when i is BackwardsIndex: s.len - int(i) else: int(i))
    template halfOpenEndpoints*[T](s:T, p:RangeType):(int,int) =
      (s^^p.a, s^^p.b + 1)
  
# source: src/atcoder/lazysegtree.nim
when not declared ATCODER_LAZYSEGTREE_HPP:
  const ATCODER_LAZYSEGTREE_HPP* = 1
  
  import std/sequtils
  import std/algorithm
  {.push inline.}
  type LazySegTree*[S,F;p:static[tuple]] = object
    len*, size*, log*:int
    d*:seq[S]
    lz*:seq[F]

  template calc_op*[ST:LazySegTree](self:ST or typedesc[ST], a, b:ST.S):auto =
    block:
      let u = ST.p.op(a, b)
      u
  template calc_e*[ST:LazySegTree](self:ST or typedesc[ST]):auto =
    block:
      let u = ST.p.e()
      u
  template calc_mapping*[ST:LazySegTree](self:ST or typedesc[ST], a:ST.F, b:ST.S):auto =
    block:
      let u = ST.p.mapping(a, b)
      u
  template calc_composition*[ST:LazySegTree](self:ST or typedesc[ST], a, b:ST.F):auto =
    block:
      # こう書かないとバグる事象を検出
      let u = ST.p.composition(a, b)
      u
  template calc_id*[ST:LazySegTree](self:ST or typedesc[ST]):auto =
    block:
      let u = ST.p.id()
      u

  proc update[ST:LazySegTree](self:var ST, k:int) =
    self.d[k] = ST.calc_op(self.d[2 * k], self.d[2 * k + 1])
  proc all_apply*[ST:LazySegTree](self:var ST, k:int, f:ST.F) =
    self.d[k] = ST.calc_mapping(f, self.d[k])
    if k < self.size:
      self.lz[k] = ST.calc_composition(f, self.lz[k])
  proc all_apply*[ST:LazySegTree](self:var ST, f:ST.F) =
    self.all_apply(1, f)
  proc push*[ST:LazySegTree](self: var ST, k:int) =
    self.all_apply(2 * k, self.lz[k])
    self.all_apply(2 * k + 1, self.lz[k])
    self.lz[k] = ST.calc_id()

  proc init[ST:LazySegTree](self:var ST, v:seq[ST.S]) =
    let
      n = v.len
      log = ceil_pow2(n)
      size = 1 shl log
    (self.len, self.size, self.log) = (n, size, log)
    if self.d.len < 2 * size:
      self.d = newSeqWith(2 * size, ST.calc_e())
    else:
      self.d.fill(0, 2 * size - 1, ST.calc_e())
    for i in 0..<n:
      self.d[size + i] = v[i]
    if self.lz.len < size:
      self.lz = newSeqWith(size, ST.calc_id())
    else:
      self.lz.fill(0, size - 1, ST.calc_id())
    for i in countdown(size - 1, 1): self.update(i)
  proc init*[ST:LazySegTree](self: var ST, n:int) = self.init(newSeqWith(n, ST.calc_e()))
  proc init*[ST:LazySegTree](self: typedesc[ST], v:seq[ST.S] or int):ST = result.init(v)

  template LazySegTreeType[S, F](op0, e0, mapping0, composition0, id0:untyped):typedesc[LazySegTree] =
    proc op1(a, b:S):S {.gensym inline.} = op0(a, b)
    proc e1():S {.gensym inline.} = e0()
    proc mapping1(f:F, s:S):S {.gensym inline.} = mapping0(f, s)
    proc composition1(f1, f2:F):F {.gensym inline.} = composition0(f1, f2)
    proc id1():F {.gensym inline.} = id0()
    LazySegTree[S, F, (op:op1, e:e1, mapping:mapping1, composition:composition1, id:id1)]

  template getType*(ST:typedesc[LazySegTree], S, F:typedesc, op, e, mapping, composition, id:untyped):typedesc[LazySegTree] =
    LazySegTreeType[S, F](op, e, mapping, composition, id)

  template initLazySegTree*[S, F](v:seq[S] or int, op, e, mapping, composition, id:untyped):auto =
    LazySegTreeType[S, F](op, e, mapping, composition, id).init(v)

  proc set*[ST:LazySegTree](self: var ST, p:IndexType, x:ST.S) =
    var p = self^^p
    assert p in 0..<self.len
    p += self.size
    for i in countdown(self.log, 1): self.push(p shr i)
    self.d[p] = x
    for i in 1..self.log: self.update(p shr i)

  proc get*[ST:LazySegTree](self: var ST, p:IndexType):ST.S =
    var p = self^^p
    assert p in 0..<self.len
    p += self.size
    for i in countdown(self.log, 1): self.push(p shr i)
    return self.d[p]

  proc `[]=`*[ST:LazySegTree](self: var ST, p:IndexType, x:ST.S) = self.set(p, x)
  proc `[]`*[ST:LazySegTree](self: var ST, p:IndexType):ST.S = self.get(p)

  proc prod*[ST:LazySegTree](self:var ST, p:RangeType):ST.S =
    var (l, r) = self.halfOpenEndpoints(p)
    assert 0 <= l and l <= r and r <= self.len
    if l == r: return ST.calc_e()

    l += self.size
    r += self.size

    for i in countdown(self.log, 1):
      if ((l shr i) shl i) != l: self.push(l shr i)
      if ((r shr i) shl i) != r: self.push(r shr i)

    var sml, smr = ST.calc_e()
    while l < r:
      if (l and 1) != 0: sml = ST.calc_op(sml, self.d[l]);l.inc
      if (r and 1) != 0: r.dec;smr = ST.calc_op(self.d[r], smr)
      l = l shr 1
      r = r shr 1
    return ST.calc_op(sml, smr)

  proc `[]`*[ST:LazySegTree](self: var ST, p:RangeType):ST.S = self.prod(p)

  proc all_prod*[ST:LazySegTree](self:ST):auto = self.d[1]

  proc apply*[ST:LazySegTree](self: var ST, p:IndexType, f:ST.F) =
    var p = self^^p
    assert p in 0..<self.len
    p += self.size
    for i in countdown(self.log, 1): self.push(p shr i)
    self.d[p] = ST.calc_mapping(f, self.d[p])
    for i in 1..self.log: self.update(p shr i)
  proc apply*[ST:LazySegTree](self: var ST, p:RangeType, f:ST.F) =
    var (l, r) = self.halfOpenEndpoints(p)
    assert 0 <= l and l <= r and r <= self.len
    if l == r: return

    l += self.size
    r += self.size

    for i in countdown(self.log, 1):
      if ((l shr i) shl i) != l: self.push(l shr i)
      if ((r shr i) shl i) != r: self.push((r - 1) shr i)

    block:
      var (l, r) = (l, r)
      while l < r:
        if (l and 1) != 0: self.all_apply(l, f);l.inc
        if (r and 1) != 0: r.dec;self.all_apply(r, f)
        l = l shr 1
        r = r shr 1

    for i in 1..self.log:
      if ((l shr i) shl i) != l: self.update(l shr i)
      if ((r shr i) shl i) != r: self.update((r - 1) shr i)

#  template <bool (*g)(S)> int max_right(int l) {
#    return max_right(l, [](S x) { return g(x); });
#  }
  proc max_right*[ST:LazySegTree](self:var ST, l:IndexType, g:proc(s:ST.S):bool):int =
    var l = self^^l
    assert l in 0..self.len
    assert g(ST.calc_e())
    if l == self.len: return self.len
    l += self.size
    for i in countdown(self.log, 1): self.push(l shr i)
    var sm = ST.calc_e()
    while true:
      while l mod 2 == 0: l = l shr 1
      if not g(ST.calc_op(sm, self.d[l])):
        while l < self.size:
          self.push(l)
          l = (2 * l)
          if g(ST.calc_op(sm, self.d[l])):
            sm = ST.calc_op(sm, self.d[l])
            l.inc
        return l - self.size
      sm = ST.calc_op(sm, self.d[l])
      l.inc
      if not((l and -l) != l): break
    return self.len

#  template <bool (*g)(S)> int min_left(int r) {
#    return min_left(r, [](S x) { return g(x); });
#  }
  proc min_left*[ST:LazySegTree](self: var ST, r:IndexType, g:proc(s:ST.S):bool):int =
    var r = self^^r
    assert r in 0..self.len
    assert(g(ST.calc_e()))
    if r == 0: return 0
    r += self.size
    for i in countdown(self.log, 1): self.push((r - 1) shr i)
    var sm = ST.calc_e()
    while true:
      r.dec
      while r > 1 and r mod 2 == 1: r = r shr 1
      if not g(ST.calc_op(self.d[r], sm)):
        while r < self.size:
          self.push(r)
          r = (2 * r + 1)
          if g(ST.calc_op(self.d[r], sm)):
            sm = ST.calc_op(self.d[r], sm)
            r.dec
        return r + 1 - self.size
      sm = ST.calc_op(self.d[r], sm)
      if not ((r and -r) != r): break
    return 0
  {.pop.}

# source: src/cplib/utils/binary_search.nim
when not declared CPLIB_UTILS_BINARY_SEARCH:
    const CPLIB_UTILS_BINARY_SEARCH* = 1
    proc meguru_bisect*(ok, ng: int, is_ok: proc(x: int): bool): int =
        var
            ok = ok
            ng = ng
        while abs(ok - ng) > 1:
            var mid = (ok + ng) div 2
            if is_ok(mid): ok = mid
            else: ng = mid
        return ok

    proc meguru_bisect*(ok, ng: SomeFloat, is_ok: proc(x: SomeFloat): bool, eps: SomeFloat = 1e-10): SomeFloat =
        var
            ok = ok
            ng = ng
        while abs(ok - ng) > eps and abs(ok - ng) / max(ok, ng) > eps:
            var mid = (ok + ng) / 2
            if is_ok(mid): ok = mid
            else: ng = mid
        return ok

# source: src/cplib/collections/segtree.nim
when not declared CPLIB_COLLECTIONS_SEGTREE:
    const CPLIB_COLLECTIONS_SEGTREE* = 1
    import algorithm
    import strutils
    import sequtils
    type SegmentTree*[T] = ref object
        default: T
        merge: proc(x: T, y: T): T
        arr*: seq[T]
        lastnode: int
        length: int
    proc initSegmentTree*[T](v: seq[T], merge: proc(x: T, y: T): T, default: T): SegmentTree[T] =
        var lastnode = 1
        while lastnode < len(v):
            lastnode*=2
        var arr = newSeq[T](2*lastnode)
        arr.fill(default)
        var self = SegmentTree[T](default: default, merge: merge, arr: arr, lastnode: lastnode, length: len(v))
        #1-indexedで作成する
        for i in 0..<len(v):
            self.arr[self.lastnode+i] = v[i]
        for i in countdown(lastnode-1, 1):
            self.arr[i] = self.merge(self.arr[2*i], self.arr[2*i+1])
        return self
    proc initSegmentTree*[T](n: int, merge: proc(x: T, y: T): T, default: T): SegmentTree[T] =
        initSegmentTree(newSeqWith(n, default), merge, default)

    proc update*[T](self: SegmentTree[T], x: Natural, val: T) =
        assert x < self.length
        var x = x
        x += self.lastnode
        self.arr[x] = val
        while x > 1:
            x = x shr 1
            self.arr[x] = self.merge(self.arr[2*x], self.arr[2*x+1])
    proc get*[T](self: SegmentTree[T], q_left: Natural, q_right: Natural): T =
        assert q_left <= q_right and 0 <= q_left and q_right <= self.length
        var q_left = q_left
        var q_right = q_right
        q_left += self.lastnode
        q_right += self.lastnode
        var (lres, rres) = (self.default, self.default)
        while q_left < q_right:
            if (q_left and 1) > 0:
                lres = self.merge(lres, self.arr[q_left])
                q_left += 1
            if (q_right and 1) > 0:
                q_right -= 1
                rres = self.merge(self.arr[q_right], rres)
            q_left = q_left shr 1
            q_right = q_right shr 1
        return self.merge(lres, rres)
    proc get*[T](self: SegmentTree[T], segment: HSlice[int, int]): T =
        assert segment.a <= segment.b + 1 and 0 <= segment.a and segment.b+1 <= self.length
        return self.get(segment.a, segment.b+1)
    proc `[]`*[T](self: SegmentTree[T], segment: HSlice[int, int]): T = self.get(segment)
    proc `[]`*[T](self: SegmentTree[T], index: Natural): T =
        assert index < self.length
        return self.arr[index+self.lastnode]
    proc `[]=`*[T](self: SegmentTree[T], index: Natural, val: T) =
        assert index < self.length
        self.update(index, val)
    proc get_all*[T](self: SegmentTree[T]): T =
        return self.arr[1]
    proc len*[T](self: SegmentTree[T]): int =
        return self.length
    proc `$`*[T](self: SegmentTree[T]): string =
        var s = self.arr.len div 2
        return self.arr[s..<s+self.len].join(" ")
    template newSegWith*(V, merge, default: untyped): untyped =
        initSegmentTree[typeof(default)](V, proc (l{.inject.}, r{.inject.}: typeof(default)): typeof(default) = merge, default)
    proc max_right*[T](self: SegmentTree[T], l: int, f: proc(l: T): bool): int =
        assert 0 <= l and l <= self.len
        assert f(self.default)
        if l == self.len: return self.len
        var l = l + self.lastnode
        var sm = self.default
        while true:
            while l mod 2 == 0: l = (l shr 1)
            if not f(self.merge(sm, self.arr[l])):
                while l < self.lastnode:
                    l *= 2
                    if f(self.merge(sm, self.arr[l])):
                        sm = self.merge(sm, self.arr[l])
                        l += 1
                return l - self.lastnode
            sm = self.merge(sm, self.arr[l])
            l += 1
            if (l and -l) == l: break
        return self.len
    proc min_left*[T](self: SegmentTree[T], r: int, f: proc(l: T): bool): int =
        assert 0 <= r and r <= self.len
        assert f(self.default)
        if r == 0: return 0
        var r = r + self.lastnode
        var sm = self.default
        while true:
            r -= 1
            while ((r > 1) and (r mod 2 != 0)): r = (r shr 1)
            if not f(self.merge(self.arr[r], sm)):
                while r < self.lastnode:
                    r = 2 * r + 1
                    if f(self.merge(self.arr[r], sm)):
                        sm = self.merge(self.arr[r], sm)
                        r -= 1
                return r + 1 - self.lastnode
            sm = self.merge(self.arr[r], sm)
            if (r and -r) == r: break
        return 0



proc initRangeAddRangeMinSegtree[T](v:seq[T]):auto=
    type S = (T,int)
    type F = T
    proc op(a,b:S):S=
        if a[0] == b[0]:
            return (a[0],a[1]+b[1])
        elif a[0] < b[0]:
            return a
        else:
            return b
    proc e():S=(INF,1)
    proc mapping(f:F,x:S):S=(x[0]+f,x[1])
    proc composition(f,g:F):F=f+g
    proc id():F=0
    return LazySegTree.getType(S, F, op, e, mapping, composition, id).init(v.mapit((it,1)))

var N = ii()

var G = initUnWeightedUnDirectedGraph(N)

# クエリ1 : 色反転
# クエリ2 : yを根としたときに、xが含まれないような部分木に含まれる黒色の頂点の数を出力

# クエリ2はyを根としたときにxが含まれるような部分木に含まれる黒色の頂点の数と解釈可能

# x = y : すべての黒色頂点
# yが黒 : それも含む

# 部分木クエリといえばオイラーツアーだが...


# range add range 最小値カウント
# -> 遅延セグ木に乗る

# hldするなどの行為により部分木クエリは可能になった。

# xがyの子孫にあるとき : yについて部分木クエリ - yからx方向に1進んだ頂点から部分木クエリ + 親方向
# 親方向ってどうやってやるんだ???????

# 親方向ではじめて別の部分木に頂点があるところを見つけて、そこの部分木クエリから - yからx方向に1進んだ頂点から部分木クエリ

# yがxの子孫にあるとき : yについて部分木クエリ


for _ in range(N-1):
    var a,b = ii()-1
    G.add_edge(a,b)
var tmp = lii(N)
var C = newsegwith(N,l+r,0)
var T = G.initHld(0)
for i in range(N):
    C[T.toseq(i)] = tmp[i]

var st = initRangeAddRangeMinSegtree(newseqwith(N,0))

for i in range(N):
    if C[T.toseq(i)] == 1:
        for (l,r) in T.path(0,i,true,false):
            st.apply(l..<r,1)

var Q = ii()
for _ in range(Q):
    var t = ii()
    if t == 1:
        var v = ii()-1
        if C[T.toseq(v)] == 1:
            for (l,r) in T.path(0,v,true,false):
                st.apply(l..<r,-1)
        else:
            for (l,r) in T.path(0,v,true,false):
                st.apply(l..<r,1)
        C[T.toseq(v)] = C[T.toseq(v)] ^ 1
    else:
        #echo C
        #echo (0..<N).toseq().mapit(T.toseq(it)).mapit(C[it])
        var x,y = ii()-1
        var (l,r) = T.subtree(y)
        proc get_subtree_query(x:int):int=
            # 部分木内の黒色の頂点を全て含むために必要な頂点数
            var (l,r) = T.subtree(x)
            var res = st[l..<r]
            #544echo res
            if res[0] != 0:
                return r-l
            return r-l-res[1]
        
        proc all_black_lca(ROOT:int=0):int=
            # すべての黒色の頂点のlca
            # 適当な黒色の頂点を取ってあげる。
            proc f(x:int):bool=
                return x <= 0
            var x = T.toVtx(C.max_right(T.toseq(ROOT),f))
            #echo "?",x
            if x == ROOT:
                return ROOT
            # その頂点から上方向に二分探索
            #echo "!",x
            #echo C
            var tmp = T.la(0,x,1)
            if st[T.toseq(ROOT)][0] != st[T.toseq(tmp)][0]:
                return 0
            var dist = T.dist(ROOT,x)
            proc is_ok(arg:int):bool=
                var x = T.la(ROOT,x,arg)
                return st[T.toseq(ROOT)][0] == st[T.toseq(x)][0]
            var res = meguru_bisect(0,dist+1,is_ok)
            #echo "res:",res
            var root = T.la(ROOT,x,res)
            #echo "root:",root
            return root
        if C.get_all() == 0:
            echo 0
            continue
        if x == y:
            # 黒色全て
            # 黒色頂点たちすべてのlcaが求めたい。
            if C.get_all() == 0:
                echo 0
            else:
                var lca = all_black_lca()
                #echo "lca:",lca
                echo get_subtree_query(lca)
        elif y == 0:
            var lca = all_black_lca()
            if lca == 0:
                var z = T.la(y,x,1)
                echo get_subtree_query(0) - get_subtree_query(z)
            else:
                echo get_subtree_query(lca)
        elif T.toseq(x) notin l..<r:
            # xがyの子孫でないパターン
            if st[T.toseq(y)][0] == 0:
                echo 0
            else:
                var tmp = all_black_lca(y)
                #echo "!",tmp
                echo get_subtree_query(tmp)
        else:
            # xがyの子孫であるパターン
            if st[T.toseq(y)][0] == 0:
                var lca = all_black_lca()
                echo get_subtree_query(lca)
            else:
                var z = T.la(y,x,1)
                #echo "!",st[T.toseq(y)][0] ," ", st[T.toseq(z)][0]," ",get_subtree_query(z)," ",z
                if st[T.toseq(y)][0] != st[T.toseq(z)][0]:
                    var lca = all_black_lca()
                    echo get_subtree_query(lca) - get_subtree_query(z)
                else:
                    var dist = T.dist(0,y)
                    proc is_ok(arg:int):bool=
                        var x = T.la(y,0,arg)
                        return st[T.toseq(0)][0] == st[T.toseq(y)][0]
                    var res = meguru_bisect(0,dist,is_ok)
                    var root = T.la(0,y,res)
                    var lca = all_black_lca()
                    echo get_subtree_query(lca)-get_subtree_query(root)

0