티스토리 뷰

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
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함