백준 14950 - 정복자

Minjae An·2023년 10월 1일
0

PS

목록 보기
97/143

문제

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

리뷰

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

기존의 MST 문제들과 다른 점은 간선을 하나 채택할 때마다 비용이 WW 만큼
증가한다는 조건이었다. 이를 구현하기 위해 크루스칼 로직을 실행하며 MST 총 비용을
구하는 과정에서 채택된 간선의 수(selected )에 W를 곱하여 현재까지 누적된
비용(total)에 더해주었다.

로직의 시간복잡도는 크루스칼의 O(NlogM)O(NlogM)으로 수렴하고 이는 N=10,000N=10,000,
M=30,000M=30,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 W = parseInt(st.nextToken());

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

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

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

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

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

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

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

        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개의 댓글