8. 응급실
N명의 대기목록 순서의 환자 위험도가 주어지면, 대기목록상의 M번째 환자는 몇 번째로 진료를 받는지 출력하는 프로그램
환자가 접수한 순서대로의 목록에서 제일 앞에 있는 환자목록을 꺼냅니다.
나머지 대기 목록에서 꺼낸 환자 보다 위험도가 높은 환자가 존재하면 대기목록 제일 뒤로 다시 넣습니다. 그렇지 않으면 진료를 받습니다.
입력) 첫 줄에 자연수 N(5<=N<=100)과 M(0<=M<N)이 주어집니다.
두 번째 줄에 접수한 순서대로 환자의 위험도(50<=위험도<=100)가 주어집니다.
출력) M번째 환자는 몇 번째로 진료받는지 출력하세요.
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Patient { // 환자 instance
int id; // 접수 순서
int priority; // 위험도(우선순위)
public Patient(int id, int danger) {
this.id = id;
this.priority = danger;
}
}
public class Main {
public static int solution(int n, int m, int[] arr) {
int answer = 0;
Queue<Patient> queue = new LinkedList<>();
for (int i=0; i<n; i++) {
queue.offer(new Patient(i,arr[i]));
}
while (!queue.isEmpty()) {
Patient temp = queue.poll();
for (Patient x : queue) {
// temp 환자보다 위험도 높은 환자 존재하는 경우
if (temp.priority<x.priority) {
queue.offer(temp); // temp 환자를 맨뒤로
temp = null;
break;
}
}
if (temp!=null) { // 진료 받는 환자
answer++;
if (temp.id==m) return answer; // m번째 환자인 경우
}
}
return answer;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // n명의 환자
int m = scanner.nextInt(); // m번째 환자
int[] arr = new int[n];
for (int i=0; i<n; i++) {
arr[i] = scanner.nextInt(); // 대기목록 순서의 환자 위험도
}
System.out.println(solution(n,m,arr));
}
}
결과
입력
5 2
60 50 70 80 90
출력
3
'알고리즘(Java) > Stack & Queue' 카테고리의 다른 글
[알고리즘]Queue - 교육과정 설계 (0) | 2021.08.07 |
---|---|
[알고리즘]Queue - 공주 구하기 (0) | 2021.08.07 |
[알고리즘]Stack - 쇠막대기 (0) | 2021.08.05 |
★[알고리즘]Stack - 후위식 연산(postfix) (0) | 2021.08.05 |
[알고리즘]Stack - 크레인 인형뽑기(카카오) (0) | 2021.08.04 |
댓글