백준 28119 - Traveling SCCC President

Minjae An·2023년 10월 2일
0

PS

목록 보기
99/143

문제

https://www.acmicpc.net/problem/28119

리뷰

크루스칼을 이용해 풀이할 수 있는 간단한 문제였다.

특정 순서에 따라 차례로 건물에서 회의를 진행할때 건물 간 총 이동 시간의
최소값을 구하는 문제였다. 하지만, 순간이동 이라는 조건이 붙기 때문에 사실
S와 방문하는 건물의 순서는 별 의미를 가지지 않는다.

따라서 그저 간선 정보를 받아 비용 기준 최소힙에 저장한 후, 크루스칼을 통해
MST를 형성하며 총 비용을 구하면 답이 된다.

로직의 시간복잡도는 크루스칼의 O(NlogM)O(NlogM)으로 수렴하고 이는 N=2,000N=2,000,
M=5,000M=5,000인 최악의 경우에도 무난히 제한 조건 2초를 통과한다.

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

import static java.lang.Integer.*;

public class Main {
    static int[] parent;
    static PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.w));

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = parseInt(st.nextToken());
        int M = parseInt(st.nextToken());
        int S = parseInt(st.nextToken());

        parent = new int[N + 1];
        int u, v, w;
        while (M-- > 0) {
            st = new StringTokenizer(br.readLine());
            u = parseInt(st.nextToken());
            v = parseInt(st.nextToken());
            w = parseInt(st.nextToken());

            pq.offer(new Edge(u, v, w));
        }

        br.readLine();
        System.out.println(kruskal(N));
        br.close();
    }

    static int kruskal(int N) {
        Arrays.fill(parent, -1);
        int selected = 0, total = 0;

        while (!pq.isEmpty() && selected < N - 1) {
            Edge e = pq.poll();

            if (!union(e.u, e.v)) continue;

            selected++;
            total += e.w;
        }

        return total;
    }

    static boolean union(int u, int v) {
        int r1 = find(u);
        int r2 = find(v);

        if (r1 == r2) return false;

        if (parent[r1] < parent[r2]) {
            parent[r1] += parent[r2];
            parent[r2] = r1;
        } else {
            parent[r2] += parent[r1];
            parent[r1] = r2;
        }

        return true;
    }

    static int find(int u) {
        if (parent[u] < 0) return u;

        return parent[u] = find(parent[u]);
    }

    static class Edge {
        int u, v, w;

        public Edge(int u, int v, int w) {
            this.u = u;
            this.v = v;
            this.w = w;
        }
    }
}

결과

profile
집념의 개발자

0개의 댓글