본문 바로가기
알고리즘

Java - 운영체제 (PCCP 모의고사 4번) heap

by jun.s.gi 2023. 7. 18.
728x90

https://school.programmers.co.kr/learn/courses/15008/lessons/121686

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

import java.util.*;

class Solution {
    class Node implements Comparable<Node>{
        long rank, arrive, runtime;
        public Node(long rank, long arrive, long runtime) {
            this.rank = rank;
            this.arrive = arrive;
            this.runtime = runtime;
        }
        @Override
        public int compareTo(Node o) { // 순위가 같다면 먼저 도착한 프로그램부터 위치시킵니다.
            if (Long.compare(this.rank, o.rank) != 0)
                return Long.compare(this.rank, o.rank);
            else return Long.compare(this.arrive, o.arrive);
        }
    }
    public long[] solution(int[][] program) {
        long[] answer = new long[11];
        PriorityQueue<Node> pro = new PriorityQueue<>(); // 순위가 높은 Node가 먼저 poll됩니다.
        ArrayList<Node> arr = new ArrayList<>();
        int idx = 0;
        long currentTime = 0;
        for(int[] i : program) arr.add(new Node(i[0], i[1], i[2]));
        arr.sort(new Comparator<Node>() { // 도착 순서대로 정렬합니다.
            @Override
            public int compare(Node o1, Node o2) {
                return Long.compare(o1.arrive, o2.arrive);
            }
        });

        idx = 0; currentTime = 0;

        while(idx < arr.size() || !pro.isEmpty()){ // idx가 끝까지 갔거나 우선순위 큐가 비어있을 때까지

            for(; idx < arr.size() ; idx++){
                if (arr.get(idx).arrive <= currentTime){ // 현재 시간까지 호출된 Node offer
                    pro.offer(arr.get(idx));
                }else break;
            }

            if(!pro.isEmpty()){ // 만약 큐에 Node가 있다면
                Node temp = pro.poll();
                System.out.println(temp);
                // 현재 시간 - 프로그램 도착시간 -> 대기 시간
                answer[(int)temp.rank] += currentTime - temp.arrive ;
                // 현재 시간 + 프로그램 실행시간
                currentTime += temp.runtime;
                answer[0] = currentTime;
            }else currentTime++; // 만약 큐가 비어있거나 프로그램이 전부 도착하지 않았을 때 
            //현재 시간에 1 더합니다.
        }
        return answer;
    }
}
728x90