본문 바로가기

Hub Algorithm/위상 정렬

[BOJ] 백준 1516 : 게임 개발 (java)

728x90

🧪 1516 게임 개발


난이도 : 🌟 골드 3
유형 : 위상 정렬

 

1516번: 게임 개발

첫째 줄에 건물의 종류 수 N(1 ≤ N ≤ 500)이 주어진다. 다음 N개의 줄에는 각 건물을 짓는데 걸리는 시간과 그 건물을 짓기 위해 먼저 지어져야 하는 건물들의 번호가 주어진다. 건물의 번호는 1부

www.acmicpc.net

 

📝 문제


숌 회사에서 이번에 새로운 전략 시뮬레이션 게임 세준 크래프트를 개발하기로 하였다. 핵심적인 부분은 개발이 끝난 상태고, 종족별 균형과 전체 게임 시간 등을 조절하는 부분만 남아 있었다.

게임 플레이에 들어가는 시간은 상황에 따라 다를 수 있기 때문에, 모든 건물을 짓는 데 걸리는 최소의 시간을 이용하여 근사하기로 하였다. 물론, 어떤 건물을 짓기 위해서 다른 건물을 먼저 지어야 할 수도 있기 때문에 문제가 단순하지만은 않을 수도 있다. 예를 들면 스타크래프트에서 벙커를 짓기 위해서는 배럭을 먼저 지어야 하기 때문에, 배럭을 먼저 지은 뒤 벙커를 지어야 한다. 여러 개의 건물을 동시에 지을 수 있다.

편의상 자원은 무한히 많이 가지고 있고, 건물을 짓는 명령을 내리기까지는 시간이 걸리지 않는다고 가정하자.

 

입력

 

첫째 줄에 건물의 종류 수 N(1 ≤ N ≤ 500)이 주어진다. 다음 N개의 줄에는 각 건물을 짓는 데 걸리는 시간과 그 건물을 짓기 위해 먼저 지어져야 하는 건물들의 번호가 주어진다. 건물의 번호는 1부터 N까지로 하고, 각 줄은 -1로 끝난다고 하자. 각 건물을 짓는데 걸리는 시간은 100,000보다 작거나 같은 자연수이다. 모든 건물을 짓는 것이 가능한 입력만 주어진다.

 

출력

 

N개의 각 건물이 완성되기까지 걸리는 최소 시간을 출력한다.

 

🚧  주의할 점


1. 건물들이 동시에 지어지기 때문에 우선순위 큐 혹은 위상정렬을 활용해야 한다.

 

🧐 핵심 로직


  각 노드의 진입차수를 저장할 indegree 배열을 만든다.

  진입차수가 0인 노드를 큐에 넣는다.

  큐가 빌 때까지 큐에서 원소를 꺼내 해당 노드에서 나가는 간선을 그래프에서 제거

  새롭게 진입차수가 0이 된 노드를 큐에 삽입

  3 ~ 4 를 반복한다.

 

💻 최종 코드 (324 ms)


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

public class Main {

    static int n;
    static int[] times;
    static int[] indegree;
    static int[] res;
    static List<List<Integer>> targets;

    public static void main(String[] args) throws IOException {

//        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader br = new BufferedReader(new FileReader("input.txt"));

        n = Integer.parseInt(br.readLine());
        targets = new ArrayList<>();
        indegree = new int[n + 1];
        times = new int[n + 1];
        res = new int[n + 1];

        for (int i = 0; i <= n; i++) {
            targets.add(new ArrayList<>());
        }

        for (int i = 1; i <= n; i++) {
            String[] words = br.readLine().split(" ");
            int idx = 1;
            times[i] = Integer.parseInt(words[0]);

            while (Integer.parseInt(words[idx]) != -1) {
                targets.get(Integer.parseInt(words[idx])).add(i);
                indegree[i]++;
                idx++;
            }
        }

        topologicalSort();

        for (int i = 1; i <= n; i++) {
            System.out.println(res[i]);
        }

        br.close();
    }

    private static void topologicalSort() {
        Queue<Integer> q = new LinkedList<>();

        for (int i = 1; i < n+1; i++) {
            if (indegree[i] == 0) {
                q.offer(i);
            }
        }

        while (!q.isEmpty()) {
            int v = q.poll();
            res[v] += times[v];

            for (int i = 0; i < targets.get(v).size(); i++) {
                int nv = targets.get(v).get(i);

                indegree[nv]--;
                if (indegree[nv] == 0) {
                    q.offer(nv);
                }

                res[nv] = Math.max(res[nv], res[v]);
            }
        }
    }
}

💻 우선 순위큐를 활용한 방식 (320 ms)


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

public class Main {

    static int n, time;
    static int[] indegree;
    static int[] res;
    static Buildings[] buildings;
    static List<List<Integer>> targets;

    static class Buildings implements Comparable<Buildings> {
        int num, time;

        Buildings(int num, int time) {
            this.num = num;
            this.time = time;
        }

        @Override
        public int compareTo(Buildings o) {
            return this.time - o.time;
        }
    }

    public static void main(String[] args) throws IOException {

//        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader br = new BufferedReader(new FileReader("input.txt"));

        n = Integer.parseInt(br.readLine());
        targets = new ArrayList<>();
        buildings = new Buildings[n + 1];
        indegree = new int[n + 1];
        res = new int[n + 1];

        for (int i = 0; i <= n; i++) {
            targets.add(new ArrayList<>());
        }

        for (int i = 1; i <= n; i++) {
            String[] words = br.readLine().split(" ");
            int idx = 1;
            time = Integer.parseInt(words[0]);
            buildings[i] = new Buildings(i, time);

            while (Integer.parseInt(words[idx]) != -1) {
                targets.get(Integer.parseInt(words[idx])).add(i);
                indegree[i]++;
                idx++;
            }
        }

        topologicalSort();

        for (int i = 1; i <= n; i++) {
            System.out.println(buildings[i].time);
        }

        br.close();
    }

    private static void topologicalSort() {
        PriorityQueue<Buildings> pq = new PriorityQueue<>();

        for (int i = 1; i < n+1; i++) {
            if (indegree[i] == 0) {
                pq.offer(buildings[i]);
            }
        }

        while (!pq.isEmpty()) {
            int now = pq.poll().num;

            for (int next : targets.get(now)) {
                indegree[next]--;

                if (indegree[next] == 0) {
                    buildings[next].time += buildings[now].time;
                    pq.offer(new Buildings(next, buildings[next].time));
                }
            }
        }
    }
}
 

'Hub Algorithm > 위상 정렬' 카테고리의 다른 글

[BOJ] 백준 1005 : ACM Craft (java)  (3) 2024.07.23
[BOJ] 백준 5021 : 왕위 계승 (java)  (0) 2024.07.05