티스토리 뷰
https://www.acmicpc.net/problem/1647
1647번: 도시 분할 계획
첫째 줄에 집의 개수 N, 길의 개수 M이 주어진다. N은 2이상 100,000이하인 정수이고, M은 1이상 1,000,000이하인 정수이다. 그 다음 줄부터 M줄에 걸쳐 길의 정보가 A B C 세 개의 정수로 주어지는데 A번
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);
console.log(x, y, cost);
this.mstCost += cost;
this.mstNode.add(x);
this.mstNode.add(y);
}
}
}
}
class KruskalCity extends Kruskal {
constructor(V, edges) {
super(V, edges);
this.maxCostRoute = 0;
}
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;
if (this.maxCostRoute < cost) this.maxCostRoute = cost;
this.mstNode.add(x);
this.mstNode.add(y);
}
}
}
}
const k = new KruskalCity(N + 1, input);
k.getMst();
console.log(k.mstCost - k.maxCostRoute);
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 4153번: 직각삼각형 (0) | 2023.07.03 |
---|---|
Node.js) 백준 1259번: 팰린드롬 수 (0) | 2023.07.03 |
Node.js) 백준 1197번: 최소 스패닝 트리 (0) | 2023.07.03 |
Node.js) 백준 2252번: 줄 세우기 (0) | 2023.07.03 |
Node.js) 백준 25083번: 새싹 (0) | 2023.07.03 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 동적프로그래밍
- DB 생성
- 다이나믹프로그래밍
- BFS
- 면접비
- create db
- 투포인터 연습
- 그래프
- node.js
- MOD
- 서버개발
- 다이나밍프로그래밍
- 롱베케이션
- 로드나인
- MySQL
- 최소공통조상
- create databases;
- 면접질문
- 은둔청년체험
- 서버점검
- 개발자면접
- 투포인터
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함