티스토리 뷰
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
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 1259번: 팰린드롬 수 (0) | 2023.07.03 |
---|---|
Node.js) 백준 1647번: 도시 분할 계획 (0) | 2023.07.03 |
Node.js) 백준 2252번: 줄 세우기 (0) | 2023.07.03 |
Node.js) 백준 25083번: 새싹 (0) | 2023.07.03 |
Node.js) 백준 27866번: 문자와 문자열 (0) | 2023.07.03 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 최소공통조상
- 다이나밍프로그래밍
- 서버점검
- MOD
- 동적프로그래밍
- DB 생성
- create databases;
- node.js
- 면접비
- 은둔청년체험
- 로드나인
- 면접질문
- 그래프
- BFS
- 서버개발
- 투포인터 연습
- 개발자면접
- MySQL
- 투포인터
- 롱베케이션
- create db
- 다이나믹프로그래밍
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함