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
'알고리즘' 카테고리의 다른 글
Python - 공주님의 정원 (2457) 그리디 (0) | 2023.07.25 |
---|---|
Python - 1로 만들기 2 (12852) 동적 계획법, 역추적 (2) | 2023.07.22 |
C++ - 창고 다각형 (2304) (0) | 2023.07.17 |
Python - 계단 오르기 (2579) DP (0) | 2023.06.29 |
Python - 흙길 보수하기 (1911) 그리디 (0) | 2023.06.29 |