티스토리 뷰

https://www.acmicpc.net/problem/24391

 

24391번: 귀찮은 해강이

첫째 줄에 강의의 개수 N(1 ≤ N ≤ 105)과 연결되어 있는 건물의 쌍의 개수 M(0 ≤ M ≤ 105)이 공백으로 구분되어 주어진다. 두 번째 줄부터는 M줄에 걸쳐 i와 j(1 ≤ i, j ≤ N)가 주어진다. 이는 i번 건

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 {
			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
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함