백준 2056 작업 (Java,자바)

jonghyukLee·2022년 1월 2일
0

이번에 풀어본 문제는
백준 2056번 작업 입니다.

📕 문제 링크

❗️코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int N;
    static int [] time,cnt;
    static List<List<Integer>> map;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());

        map = new ArrayList<>();
        for(int i = 0; i <= N; ++i) map.add(new ArrayList<>());

        StringTokenizer st;
        time = new int[N+1];
        cnt = new int[N+1];
        for(int i = 1; i <= N; ++i)
        {
            st = new StringTokenizer(br.readLine());
            time[i] = Integer.parseInt(st.nextToken());

            int t = Integer.parseInt(st.nextToken());
            for(int j = 0; j < t; ++j)
            {
                int tmp_num = Integer.parseInt(st.nextToken());

                map.get(tmp_num).add(i);
                cnt[i]++;
            }
        }

        int [] res = new int[N+1];
        Queue<Integer> q = new LinkedList<>();
        for(int i = 1; i <= N; ++i)
        {
            res[i] = time[i];
            if(cnt[i] == 0)
            {
                q.add(i);
            }
        }

        while(!q.isEmpty())
        {
            int cur = q.poll();


            for(int next : map.get(cur))
            {
                cnt[next]--;

                res[next] = Math.max(res[next],res[cur]+time[next]);
                if(cnt[next] == 0)
                {
                    q.add(next);
                }
            }
        }
        int answer = Integer.MIN_VALUE;
        for(int i : res)
        {
            if(answer < i) answer = i;
        }
        System.out.print(answer);
    }
}

📝 풀이

선행되어야 할 작업이 끝나면 자신의 작업도 수행할 수 있으며, 동시수행도 상관없는 조건의 위상정렬 문제입니다.
List내에 각 노드들의 연결을 저장해주고, 선행되어야 할 작업들의 카운트를 쌓아둡니다. 작업의 진행에 따라 자신을 선행작업으로 두고있는 작업들의 카운트를 줄여나가면서, 그 카운트가 0이 되었을 경우에는 해당 작업도 큐에 담아 진행될 수 있도록 합니다. 시간은 res 배열에서 항상 해당 작업시점의 최댓값으로 최신화 시켜주어 마지막 정답을 도출해낼 수 있게됩니다.

📜 후기

최소 시간을 구하는 부분이 조금 어려웠던 것 같습니다.

profile
머무르지 않기!

0개의 댓글