Problem:
Score : 100 points

Problem Statement

You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.

0 u v: Add an edge (u, v).

1 u v: Print 1 if u and v are in the same connected component, 0 otherwise.

Constraints

1 \leq N \leq 200,000

1 \leq Q \leq 200,000

0 \leq u_i, v_i \lt N

Input

Input is given from Standard Input in the following format:

N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q

出力

For each query of the latter type, print the answer.

Sample Input 1

4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3

Sample Output 1

0
1
0
1

Solution in Kotlin (1.3.71) (judge verdict: Accepted)

fun main(args : Array<String>) {
    val (n, q) = readLine()!!.split(" ").map { it.toInt() }
    val uf = UnionFind(n)

    repeat(q) {
        val (t, u, v) = readLine()!!.split(" ").map { it.toInt() }

        if (t == 0) {
            uf.merge(u, v)
        } else {
            println(if (uf.isSame(u, v)) 1 else 0)
        }
    }
}

// Union Find
// NOTE: initSize is the number of elements
private data class UnionFind(val initSize: Int) {
    private val parents = IntArray(this.initSize) { it }
    private val sizes = LongArray(this.initSize) { 1L }

    fun root(idx: Int): Int {
        if (idx == parents[idx]) return idx

        val rootP = root(parents[idx])
        parents[idx] = rootP
        return rootP
    }

    // NOTE: merge to the larger group
    fun merge(p1: Int, p2: Int) {
        if (this.isSame(p1, p2)) return

        val rootP1 = root(p1)
        val rootP2 = root(p2)

        if (this.sizes[rootP1] >= this.sizes[rootP2]) {
            this.sizes[rootP1] += this.sizes[rootP2]
            this.parents[rootP2] = this.parents[rootP1]
        } else {
            this.sizes[rootP2] += this.sizes[rootP1]
            this.parents[rootP1] = this.parents[rootP2]
        }
    }

    fun isSame(p1: Int, p2: Int): Boolean {
        return this.root(p1) == this.root(p2)
    }

    fun size(idx: Int): Long {
        return this.sizes[this.root(idx)]
    }
}