본문 바로가기
코딩테스트

[백준] 1647번 '도시 분할 계획' - Java

by CuckooBird 2023. 8. 5.

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.io.*;
import java.util.*;

public class Main {
	public static class Node implements Comparable<Node>{
		int s;
		int e;
		int cost;
		
		public Node(int s, int e, int cost) {
			this.s = s;
			this.e = e;
			this.cost = cost;
		}
		
		@Override
		public int compareTo(Node n1) {
			return this.cost - n1.cost;
		}
	}
	private static final BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	
	private static int n, m;
	private static PriorityQueue<Node> q;
	private static int[] parent;
	
	public static void main(String[] args) throws IOException {
		StringTokenizer st = new StringTokenizer(bf.readLine());
		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());
		
		q = new PriorityQueue<>();
		for(int i = 0 ; i < m ; i++) {
			st = new StringTokenizer(bf.readLine());
			int s = Integer.parseInt(st.nextToken());
			int e = Integer.parseInt(st.nextToken());
			int cost = Integer.parseInt(st.nextToken());
			q.offer(new Node(s, e, cost));
		}
		
		parent = new int[n + 1];
		bw.write(kruscal() + "\n");
		
		bf.close();
		bw.flush();
		bw.close();
	}
	
	public static int kruscal() {
		for(int i = 1 ; i <= n ; i++) {
			parent[i] = i;
		}
		
		int count = 0;
		int dist = 0;
		while(count < n - 2) {
			Node node = q.poll();
			int p1 = find(node.s);
			int p2 = find(node.e);
			
			if(p1 != p2) {
				union(p1, p2);
				dist += node.cost;
				count ++;
			}
		}
		return dist;
	}
	
	public static void union(int a, int b) {
		parent[a] = b;
	}
	
	public static int find(int a) {
		if(parent[a] == a) return a;
		else return parent[a] = find(parent[a]);
	}
}

설명은.. 내일 쓸게요.. 이 모든 건 이 썩어빠진 세상 때문입니다........


Search

https://moonsbeen.tistory.com/145