티스토리 뷰

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
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함