백준 16398번 JAVA : 행성 연결

문제

백준 문제 링크 : https://www.acmicpc.net/problem/16398

풀이전략

각 행성간의 플로우 관리비용의 최소값을 구하면 된다. 최소신장트리를 구하면 되는 문제이므로 크루스칼 알고리즘을 사용하여 문제를 해결한다.

코드

import java.io.*;
import java.util.*;

public class Main {

	static class Edge{
		public int a, b, dis;
		public Edge(int a, int b, int dis){
			this.a = a;
			this.b = b;
			this.dis = dis;
		}
	}

	static int N, M;
	static int[] graph;
	static ArrayList<Edge> edge;

	static int find(int n) {
		if(graph[n] == n) return n;
		return graph[n] = find(graph[n]);
	}

	static void union(int a, int b) {
		graph[find(a)] = find(b);
	}

	public static void main(String[] args) throws Exception{
		System.setIn(new FileInputStream("src/input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = null;

		int N = Integer.parseInt(br.readLine());

		graph = new int[N+1];
		for(int i=0; i<=N; i++) {
			graph[i] = i;
		}
		edge = new ArrayList<>();
		for(int i=0; i<N; i++) {
			st = new StringTokenizer(br.readLine());
			for(int j=0; j<N; j++) {
				int c = Integer.parseInt(st.nextToken());
				if(j <= i) continue;
				edge.add(new Edge(i,j,c));
			}
		}

		edge.sort((e1, e2) -> e1.dis - e2.dis);
		long answer = 0;
		for(int i=0; i<edge.size(); i++) {
			Edge now = edge.get(i);
			if(find(now.a) != find(now.b)) {
				union(now.a, now.b);
				answer+=now.dis;
			}
		}
		System.out.println(answer);
	}
}

회고

  • 크루스칼 알고리즘의 정석문제였다. 알고리즘을 잊지 않도록 자주 복습하도록 하자.

Written by@Gomster
항상 노력하고 나아가는 백엔드 개발자가 되고 싶은 대학생입니다.

GitHub