DEV Community

素集合データ構造 (Disjoin-set または Union-Find)

コード

const Node = function (val) {
  this.val = val
  this.parent = this
  this.rank = 1
}

const DisjointSet = function () {
  this.m = []
}

DisjointSet.prototype.add = function (val) {
  this.m[val] = new Node(val)
}

DisjointSet.prototype.union = function (val1, val2) {
  const p1 = this.find(this.m[val1].val)
  const p2 = this.find(this.m[val2].val)
  if (p1 === p2) {
    return
  }
  if (p1.rank === p2.rank) {
    p2.rank++
    p1.parent = p2
  } else if (p1.rank < p2.rank) {
    p1.parent = p2
  } else {
    p2.parent = p1
  }
}

DisjointSet.prototype.find = function (val) {
  let cur = this.m[val]
  if (cur.parent != cur) {
    cur.parent = this.find(cur.parent.val)
  }
  return cur.parent
}

let input = require('fs').readFileSync('/dev/stdin', 'utf8');
const lines = input.trim().split("\n")
let n, q, d

for (let i = 0; i < lines.length; i++) {
  if (i === 0) {
    [n, q] = lines[i].split(" ")
    d = new DisjointSet()
    for (let i = 0; i < n; i++) {
      d.add(i)
    }
  } else {
    const [com, x, y] = lines[i].split(" ").map(v => parseInt(v))
    switch (com) {
      case 0:
        d.union(x, y)
        break;
      case 1:
        console.log(d.find(x) === d.find(y) ? 1 : 0)
        break;
      default:
        throw Error('invalid com')
    }
  }
}

問題

Top comments (0)