DEV Community

2 3

素集合データ構造 (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')
    }
  }
}

問題

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay