728x90

 

 

문제

 

 

 

풀이

큐를 사용하는 문제이다. 다만 큐에 저장을 할 때, 배열 형태로 저장했다. 큐의 [0]은 인덱스 번호, 큐의 [1]은 필요한 피자의 양이다.

그래서 큐를 LinkedList<int []> queue 로 선언했다.

 

핵심 로직은 다음과 같다. 큐가 빌 때 까지 반복한다.

  • 시간을 1 증가시킨다.
  • 큐의 가장 첫 번째 요소를 가져온다.
  • 요소[0]은 고유한 사람의 인덱스 번호, 요소[1]은 필요한 피자의 양이다.
    • 요소[1]-1 이 0이라면 정답 배열의 요소[0] 값에 시간값을 넣는다.
    • 그렇지 않다면 해당 요소[0]은 그대로, 요소[1]은 -1 한 값(피자를 하나 먹었으므로!) 을 큐의 맨 뒤에 넣는다.

 

 

 

코드

package baekjoon._15235;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Main {
static StringBuilder sb = new StringBuilder();
public static String solution(LinkedList<int []> queue, int n) {
int [] answer = new int[n];
int time = 0;
while(!queue.isEmpty()) { // 큐가 빌 때 까지 반복
time++; // 일단 시간 증가
// 큐에서 첫번째 요소 꺼내기
int[] current = queue.poll();
if (current[1] - 1 == 0) { // 피자 다 먹음
answer[current[0]] = time; // 해당 인덱스 위치에 피자를 먹는데까지 걸린 시간 넣기
}
else { // 아직 피자 더 먹어야 하면
queue.offer(new int[] {current[0], current[1]-1});
}
}
for(int i : answer) {
sb.append(i).append(" ");
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
LinkedList<int[]> queue = new LinkedList<>();
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for(int i = 0; i < n; i++) {
// [0] 은 인덱스 번호, [1]은 필요한 피자의 수
queue.offer(new int[] { i, Integer.parseInt(st.nextToken())});
}
bw.write(solution(queue, n));
bw.flush();
bw.close();
br.close();
}
}
728x90