프로그래머스 121686번 운영체제 Java

: ) YOUNG·2024년 3월 29일
1

알고리즘

목록 보기
343/370
post-thumbnail

프로그래머스 121686번
https://school.programmers.co.kr/learn/courses/15008/lessons/121686

문제



생각하기


  • 우선순위 큐를 활용하는 전형적인 큐 문제이다.

  • 순서에 맞게 task를 처리하는 문제



동작

내가 이런 Queue를 이용해서 task처리하는 문제에 유독 약해서 정답을 보고 문제를 해결했다.

문제 해결 방법은 진짜 실행시간과 대기시간을 하는 방법으로 해결했다.



결과


코드



import java.util.*;

public class Solution {
    
    public static class Program implements Comparable<Program> {
        int score;
        int calledTime;
        int finishedTime;

        public Program(int score, int calledTime, int finishedTime) {
            this.score = score;
            this.calledTime = calledTime;
            this.finishedTime = finishedTime;
        }

        @Override
        public int compareTo(Program o) {
            if(score == o.score) {
                return calledTime - o.calledTime;
            }
            
            return score - o.score;
        }
    } // End of Program class
    
    public static long[] solution(int[][] programs) {
        int N  = programs.length;
        
        Arrays.sort(programs, (o1, o2) -> {
            if(o1[1] == o2[1]) {
                return Integer.compare(o1[0], o2[0]);
            }
            
            return Integer.compare(o1[1], o2[1]);
        });
        
        PriorityQueue<Program> waitingQue = new PriorityQueue<>();
        long[] ans = new long[11];
        
        long time = -1;
        int run = 0;
        int idx = 0;
        
        for(;;) {
            if(idx == N && waitingQue.isEmpty() && run == 0) {
                break;
            }
            
            time++;
            if(run > 0) {
                run--;
            }
            
            while(idx < N && programs[idx][1] == time) {
                waitingQue.offer(new Program(programs[idx][0], programs[idx][1], programs[idx][2] ));
                idx++;
            }
            
            if(run == 0 && !waitingQue.isEmpty()) {
                Program current = waitingQue.poll();
                
                
                run += current.finishedTime;
                
                ans[current.score] += time - current.calledTime;
            }   
        }
        
        ans[0] = time;
        
        return ans;
    } // End of solution()
} // End of Solution class

0개의 댓글