티스토리 뷰

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

 

7511번: 소셜 네트워킹 어플리케이션

각 테스트 케이스마다 "Scenario i:"를 출력한다. i는 테스트 케이스 번호이며, 1부터 시작한다. 그 다음, 각각의 쌍마다 두 사람을 연결하는 경로가 있으면 1, 없으면 0을 출력한다. 각 테스트 케이스

www.acmicpc.net

 

class Node {
	constructor(item) {
		this.item = item;
		this.next = null;
	}
}

class Queue {
	constructor() {
		this.head = null;
		this.tail = null;
		this.length = 0;
	}

	push(item) {
		const node = new Node(item);
		if (this.head == null) {
			this.head = node;
		} else {
			this.tail.next = node;
		}

		this.tail = node;
		this.length += 1;
	}

	pop() {
		const popItem = this.head;
		this.head = this.head.next;
		this.length -= 1;
		return popItem.item;
	}
}

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 = [];
const q = new Queue();
readline.on('line', (line) => {
	q.push(line.split(' ').map(Number));
}).on('close', () => {
	const [T] = q.pop();
	for (let t = 0; t < T; t++) {
		// 유저수
		const [F] = q.pop();
		const uf = new UF(F + 1);

		// 관계를 맺어주기
		const [R] = q.pop();
		for (let r = 0; r < R; r++) {
			const [a, b] = q.pop();
			uf.union(a, b);
		}
		// 친구인지 아닌 지 확인
		const [C] = q.pop();
		const tcAnswer = [`Scenario ${t + 1}:`];
		for (let c = 0; c < C; c++) {
			const [a, b] = q.pop();
			if (uf.find(a) == uf.find(b)) {
				tcAnswer.push('1');
			} else {
				tcAnswer.push('0');
			}
		}
		answer.push(tcAnswer.join('\n'));
	}
	console.log(answer.join('\n\n'));
	process.exit();
});

// if (!T) {
// 	T = +line;
// } else if (!uf) {
// 	tcAnswer = [];
// 	F = +line;
// 	uf = new UF(F + 1);
// } else if (uf) {
// 	if (R === null) {
// 		R = +line;
// 	} else if (R > 0) {
// 		const [a, b] = line.split(' ').map(Number);
// 		uf.union(a, b);
// 		R--;
// 	} else if (C === null) {
// 		C = +line;
// 	} else if (C > 0) {
// 		const [a, b] = line.split(' ').map(Number);
// 		if (uf.find(a) == uf.find(b)) {
// 			tcAnswer.push('1');
// 		} else {
// 			tcAnswer.push('0');
// 		}
// 	}
// }

// //
// //
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
글 보관함