in.add()
[1647] 도시 분할 계획 본문
문제 링크 : 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
문제 해결 방법
오랜만에 크루스칼을 구현해봤다.
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
static class Node implements Comparable<Node> {
int from;
int to;
int cost;
public Node(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
@Override
public int compareTo(Node o) {
return this.cost - o.cost;
}
}
static int[] parent;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
PriorityQueue<Node> pq = new PriorityQueue<>();
parent = new int[N + 1];
for (int i = 0; i < M; i++) {
pq.add(new Node(sc.nextInt(), sc.nextInt(), sc.nextInt()));
}
for (int i = 0; i < N + 1; i++) {
parent[i] = i;
}
int answer = 0;
int count = 0;
while (count < N - 1) {
Node node = pq.poll();
if (find(node.from) != find(node.to)) {
union(node.from, node.to);
count++;
if(count < N - 1) answer += node.cost;
}
}
System.out.println(answer);
}
public static int find(int nodeNum) {
if (parent[nodeNum] == nodeNum) return nodeNum;
else return parent[nodeNum] = find(parent[nodeNum]);
}
public static void union(int from, int to) {
parent[find(to)] = find(from);
}
}
'Algorithm > BOJ' 카테고리의 다른 글
[16234] 인구 이동 (0) | 2021.11.05 |
---|---|
[14500] 테트로미노 (0) | 2021.10.21 |
[14503] 로봇 청소기 (0) | 2021.10.20 |
[2293] 동전 1 (0) | 2021.10.19 |
[14442] 벽 부수고 이동하기 2 (0) | 2021.10.17 |
Comments