태그 : union find

집합의 표현

문제

초기에 {0}, {1}, {2}, … {n} 이 각각 n+1개의 집합을 이루고 있다. 여기에 합집합 연산과, 두 원소가 같은 집합에 포함되어 있는지를 확인하는 연산을 수행하려고 한다.

집합을 표현하는 프로그램을 작성하시오.

입력

첫째 줄에 n(1≤n≤1,000,000), m(1≤m≤100,000)이 주어진다. m은 입력으로 주어지는 연산의 개수이다. 다음 m개의 줄에는 각각의 연산이 주어진다. 합집합은 0 a b의 형태로 입력이 주어진다. 이는 a가 포함되어 있는 집합과, b가 포함되어 있는 집합을 합친다는 의미이다. 두 원소가 같은 집합에 포함되어 있는지를 확인하는 연산은 1 a b의 형태로 입력이 주어진다. 이는 a와 b가 같은 집합에 포함되어 있는지를 확인하는 연산이다. a와 b는 n 이하의 자연수 또는 0이며 같을 수도 있다.

출력

1로 시작하는 입력에 대해서 한 줄에 하나씩 YES/NO로 결과를 출력한다. (yes/no 를 출력해도 된다)

입출력 예제

//입력1
7 8
0 1 3
1 1 7
0 7 6
1 7 1
0 3 7
0 4 2
0 1 1
1 1 1
//출력1
NO
NO
YES
👍 #. 풀이확인 JS 👍
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const input = require('fs').readFileSync('/dev/stdin')
const info = input
  .toString()
  .trim()
  .split(/\n+/)
  .map((i) =>
    i
      .toString()
      .trim()
      .split(/\s+/)
      .map((n) => +n)
  )

const [N, M] = info[0]
const data = info.slice(1)

//셋만들기
const makeSet = () => {
  const singleton = {
    rank: 0
  }
  singleton.parent = singleton
  return singleton
}
//부모리턴
const find = (node) => {
  if (node.parent !== node) {
    node.parent = find(node.parent)
  }
  return node.parent
}
//합집합
const union = (node1, node2) => {
  const root1 = find(node1)
  const root2 = find(node2)
  if (root1 !== root2) {
    if (root1.rank < root2.rank) {
      root1.parent = root2
    } else {
      root2.parent = root1
      if (root1.rank === root2.rank) root1.rank += 1
    }
  }
}

const main = () => {
  const setList = new Map()
  for (let i = 1; i <= N; i++) {
    setList.set(i, makeSet())
  }

  for (let i = 0; i < M; i++) {
    const [type, a, b] = data[i]
    if (type === 0) {
      union(setList.get(a), setList.get(b))
    } else {
      console.log(find(setList.get(a)) === find(setList.get(b)) ? 'YES' : 'NO')
    }
  }
}

main()

예제나 Math.random으로 100000까지 테스트를 진행해도 에러가 나지 않는데 백준사이트에서는 런타임에러가 발생하고 있음. 현재 질문하기에 글올려놓음.

◀️ Lets Travel OX퀴즈 ▶️
comments powered by Disqus