티스토리 뷰

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

 

1197번: 최소 스패닝 트리

첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이

www.acmicpc.net

 

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

const [N, K] = input.shift();

class Edge {
	constructor(src, dest, cost = 0) {
		this.src = src;
		this.dest = dest;
		this.cost = cost;
	}
}

class Kruskal {
	//input: [[src,dest,cost], ...]
	constructor(V, input) {
		this.mstCost = 0;
		this.mstNode = new Set();
		this.parent = Array(V)
			.fill(0)
			.map((_, i) => i);
		this.edges = [];

		input.forEach(([s, d, c]) => {
			this.edges.push(new Edge(s, d, c));
		});

		this.edges = this.edges.sort((a, b) => a.cost - b.cost);
	}

	find(i) {
		if (this.parent[i] == i) {
			return i;
		}
		return this.find(this.parent[i]);
	}

	union(x, y) {
		if (x < y) this.parent[y] = x;
		else this.parent[x] = y;
	}

	isCycle() {
		for (let i = 0; i < this.edges.length; i++) {
			const x = this.find(this.edges[i].src);
			const y = this.find(this.edges[i].dest);

			if (x == y) {
				return true;
			}

			this.union(x, y);
		}
		return false;
	}

	getMst() {
		for (let i = 0; i < this.edges.length; i++) {
			const { src, dest, cost } = this.edges[i];

			const x = this.find(src);
			const y = this.find(dest);
			if (x != y) {
				this.union(x, y);
				this.mstCost += cost;
				this.mstNode.add(x);
				this.mstNode.add(y);
			}
		}
	}
}

const k = new Kruskal(N + 1, input);
k.getMst();
console.log(k.mstCost);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함