티스토리 뷰
https://www.acmicpc.net/problem/1717
1717번: 집합의 표현
초기에 $n+1$개의 집합 $\{0\}, \{1\}, \{2\}, \dots , \{n\}$이 있다. 여기에 합집합 연산과, 두 원소가 같은 집합에 포함되어 있는지를 확인하는 연산을 수행하려고 한다. 집합을 표현하는 프로그램을 작
www.acmicpc.net
class SubSet {
constructor(i) {
this.parent = i;
this.rank = 0;
}
}
class UF {
constructor(N) {
this.subsets = Array.from(Array(N), (_, i) => {
return new SubSet(i);
});
}
find(i) {
if (this.subsets[i].parent == i) {
return i;
} else {
return this.find(this.subsets[i].parent);
}
}
union(x, y) {
const xroot = this.find(x);
const yroot = this.find(y);
if (this.subsets[xroot].rank < this.subsets[yroot].rank) {
this.subsets[xroot].parent = yroot;
} else if (this.subsets[xroot].rank > this.subsets[yroot].rank) {
this.subsets[yroot].parent = xroot;
} else {
this.subsets[xroot].parent = yroot;
this.subsets[yroot].rank++;
}
}
}
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
const answer = [];
let uf;
readline.on('line', function (line) {
const nums = line.split(' ').map(Number);
if (nums.length == 2) {
const [N, M] = nums;
uf = new UF(N + 1);
} else {
const [c, a, b] = nums;
switch (c) {
case 0: // 합집합
uf.union(a, b);
break;
case 1: // 확인
if (uf.find(a) == uf.find(b)) {
answer.push('YES');
} else {
answer.push('NO');
}
break;
}
}
}).on('close', function () {
console.log(answer.join('\n'));
process.exit();
});
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 1351번: 무한 수 (0) | 2023.08.31 |
---|---|
Node.js) 백준 11000번: 강의실 배정 (0) | 2023.08.31 |
Node.js) 백준 1247번: 부호 (0) | 2023.08.30 |
Node.js) 백준 1100번: 하얀 칸 (0) | 2023.08.29 |
Node.js) 백준 1076번: 저항 (0) | 2023.08.28 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 개발자면접
- 면접비
- create databases;
- 다이나밍프로그래밍
- 서버개발
- 서버점검
- MySQL
- 은둔청년체험
- 롱베케이션
- BFS
- 동적프로그래밍
- 다이나믹프로그래밍
- MOD
- 최소공통조상
- DB 생성
- 투포인터 연습
- node.js
- 면접질문
- 그래프
- create db
- 투포인터
- 로드나인
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함