Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
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 29 30 31
Archives
Today
Total
관리 메뉴

전공공부

[BOJ_16398] 행성 연결 본문

Study/Problem Solving

[BOJ_16398] 행성 연결

monitor 2024. 1. 10. 00:08

설명


 

프림 알고리즘을 활용하여 인접 행렬을 인접 리스트 형식으로 받아서 처리했다.

 

코드


package MST;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;


public class BOJ_16398 {
    static class Data implements Comparable<Data> {
        int end;
        int weight;

        public Data(int end, int weight) {
            this.end = end;
            this.weight = weight;
        }

        @Override
        public int compareTo(Data o) {
            return this.weight - o.weight;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());
        ArrayList<Data>[] list = new ArrayList[N + 1];
        for (int i = 0; i <= N; i++) {
            list[i] = new ArrayList<>();
        }

        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                int cost = Integer.parseInt(st.nextToken());
                list[i].add(new Data(j, cost));
            }
        }

        long result = findMinimumFlowCost(N, list);
        System.out.println(result);
    }

    private static long findMinimumFlowCost(int V, ArrayList<Data>[] list) {
        boolean[] visited = new boolean[V + 1];
        PriorityQueue<Data> pq = new PriorityQueue<>();

        pq.offer(new Data(1, 0));
        long max = 0;

        while (!pq.isEmpty()) {
            Data cur = pq.poll();

            if (visited[cur.end]) {
                continue;
            }

            visited[cur.end] = true;
            max += cur.weight;
            for (Data next : list[cur.end]) {
                if (!visited[next.end]) {
                    pq.offer(new Data(next.end, next.weight));
                }
            }
        }

        return max;
    }
}
 

16398번: 행성 연결

홍익 제국의 중심은 행성 T이다. 제국의 황제 윤석이는 행성 T에서 제국을 효과적으로 통치하기 위해서, N개의 행성 간에 플로우를 설치하려고 한다. 두 행성 간에 플로우를 설치하면 제국의 함

www.acmicpc.net

 

'Study > Problem Solving' 카테고리의 다른 글

[BOJ_21924] 도시건설  (1) 2024.01.13
[BOJ_1774] 우주신과의 교감  (1) 2024.01.13
[BOJ_1647] 도시 분할 계획  (0) 2024.01.08
[BOJ_20442] ㅋㅋ루ㅋㅋ  (0) 2024.01.07
[BOJ_20366] 같이 눈사람 만들래?  (0) 2024.01.06