티스토리 뷰

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

 

16562번: 친구비

첫 줄에 학생 수 N (1 ≤ N ≤ 10,000)과 친구관계 수 M (0 ≤ M ≤ 10,000), 가지고 있는 돈 k (1 ≤ k ≤ 10,000,000)가 주어진다. 두번째 줄에 N개의 각각의 학생이 원하는 친구비 Ai가 주어진다. (1 ≤ Ai ≤ 10,

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;
	}
}

const input = require('fs')
	.readFileSync('./dev/stdin')
	.toString()
	.trim()
	.split('\n')
	.map((v) => v.split(' ').map(Number));

// 학생수, 친구관계 수 , 가지고 있는돈
// 친구비
// 친구관게...

const [N, M, K] = input[0];
const cost = input[1];
cost.unshift(null);

const friendLink = Array.from(Array(N + 1), () => []);

for (let i = 2; i < input.length; i++) {
	const [x, y] = input[i];
	friendLink[x].push(y);
	friendLink[y].push(x);
}

const q = new Queue();

let visited = Array.from(Array(N + 1), () => false);

let need = 0;
for (let i = 1; i < N + 1; i++) {
	if (visited[i]) continue;
	q.push(i);
	visited[i] = true;
	let min = cost[i];
	while (q.length > 0) {
		const now = q.pop();
		const nowCost = cost[now];
		min = min > nowCost ? nowCost : min;
		const flist = friendLink[now];
		for (let f = 0; f < flist.length; f++) {
			const next = flist[f];
			if (visited[next]) continue;
			visited[next] = true;
			q.push(next);
		}
	}
	need += min;
}

console.log(need > K ? 'Oh no' : need);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함