0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

KotlinでUnion-Find木を実装

Last updated at Posted at 2024-10-17

KotlinでUnion-Findを実装

AtCoderにてKotlinで実装をしているのですが、KotlinにはUnion-Find木が存在しないので自前で実装します。

class UnionFind(n: Int) {
    val par = Array(n){it}
    val rank = Array(n){0}

    fun find(x: Int): Int {
        if (par[x] == x) {
            return x
        } else {
            par[x] = find(par[x])
            return par[x]
        }
    }

    fun unite(x: Int, y: Int) {
        val px = find(x)
        val py = find(y)
        if (px == py) return
        if (rank[px] < rank[py]) {
            par[px] = py
        } else {
            par[py] = px
            if (rank[px] == rank[py]) {
                rank[px] ++
            }
        }
    }

    fun same(x: Int, y: Int): Boolean {
        return find(x) == find(y)
    }

}

参考: 蟻本

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?