티스토리 뷰
https://www.acmicpc.net/problem/24391
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 {
this.subsets[i].parent = this.find(this.subsets[i].parent);
return 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,
});
let answer = 0;
let N = null;
let M = null;
let uf = null;
readline.on('line', (line) => {
const input = line.split(' ').map(Number);
if (uf == null) {
[N, M] = input;
uf = new UF(N + 1);
} else if (M > 0) {
const [a, b] = input;
uf.union(a, b);
M--;
} else {
const timeTable = input;
for (let i = 1; i < timeTable.length; i++) {
const prev = timeTable[i - 1];
const now = timeTable[i];
if (uf.find(prev) != uf.find(now)) {
answer++;
}
}
}
}).on('close', () => {
console.log(answer);
process.exit();
});
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 29767번: 점수를 최대로 (0) | 2023.09.11 |
---|---|
Node.js) 백준 29766번: DKSH 찾기 (0) | 2023.09.11 |
Node.js) 백준 25556번: 포스택 (0) | 2023.09.08 |
Node.js) 백준 22252번: 정보 상인 호석 (0) | 2023.09.07 |
Node.js) 백준 23559번: 밥 (0) | 2023.09.07 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 최소공통조상
- create databases;
- 은둔청년체험
- 다이나밍프로그래밍
- 면접비
- 동적프로그래밍
- 로드나인
- 투포인터 연습
- MOD
- 그래프
- node.js
- 다이나믹프로그래밍
- create db
- 서버개발
- 롱베케이션
- MySQL
- 투포인터
- 개발자면접
- DB 생성
- BFS
- 서버점검
- 면접질문
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함