문제.
메디컬 병원 응급실에는 의사가 한 명밖에 없습니다.
응급실은 환자가 도착한 순서대로 진료를 합니다. 하지만 위험도가 높은 환자는 빨리 응급조치를 의사가 해야 합니다.
이런 문제를 보완하기 위해 응급실은 다음과 같은 방법으로 환자의 진료순서를 정합니다.
• 환자가 접수한 순서대로의 목록에서 제일 앞에 있는 환자목록을 꺼냅니다.
• 나머지 대기 목록에서 꺼낸 환자 보다 위험도가 높은 환자가 존재하면 대기목록 제일 뒤로 다시 넣습니다. 그렇지 않으면 진료를 받습니다.
즉 대기목록에 자기 보다 위험도가 높은 환자가 없을 때 자신이 진료를 받는 구조입니다.
현재 N명의 환자가 대기목록에 있습니다.
N명의 대기목록 순서의 환자 위험도가 주어지면, 대기목록상의 M번째 환자는 몇 번째로 진료를 받는지 출력하는 프로그램을 작성하세요.
대기목록상의 M번째는 대기목록의 제일 처음 환자를 0번째로 간주하여 표현한 것입니다.
입력 예시 1
15 5
63 53 87 91 83 72 83 92 63 68 88 74 51 82 89
답 : 10
입력 예시 2
6 0
60 60 90 60 60 60
답 : 4
나의 답변
public class Main {
static class Patient {
int id;
int priority;
public Patient(int id, int priority) {
this.id = id;
this.priority = priority;
}
}
public int solution(int n, int m, int[] waitingList) {
int answer = 0;
Queue<Patient> q = new LinkedList<>();
// 환자들을 큐에 추가
for(int i=0; i<n; i++) {
q.offer(new Patient(i, waitingList[i]));
}
// 큐가 비어있기 직전까지 while문
while(!q.isEmpty()) {
Patient current = q.poll();
boolean canTreat = true;
for(int i=0; i<q.size(); i++) {
Patient compare = q.poll();
if(current.priority < compare.priority) {
q.add(current);
canTreat = false;
}else {
q.add(compare);
}
}
if(canTreat) {
answer++;
if(m==current.priority) return answer;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] waitingList = new int[n];
for( int i=0; i<n; i++ ) {
waitingList[i] = sc.nextInt();
}
System.out.print(T.solution(n, m, waitingList));
}
}
오답 : 입력예시 2는 맞으나 입력예시 1에서 답이 12가 나옴
정정 답변
public class Main {
static class Patient {
int id;
int priority;
public Patient(int id, int priority) {
this.id = id;
this.priority = priority;
}
}
public int solution(int n, int m, int[] waitingList) {
int answer = 0;
Queue<Patient> q = new LinkedList<>();
// 환자들을 큐에 추가
for(int i=0; i<n; i++) {
q.offer(new Patient(i, waitingList[i]));
}
// 큐가 비어있기 직전까지 while문
while(!q.isEmpty()) {
// 63
Patient current = q.poll();
// 대기목록에 우선권이 더 큰 환자가 있는지 여부확인
boolean canTreat = true;
// 향상된 for문에선 큐에서 데이터를 빼내는 작업을 진행하지 않고 전하게 순회
for(Patient compare : q) {
// 대기목록에 우선권이 더 큰 환자가 있을시 맨 뒤로 감
if(current.priority < compare.priority) {
q.add(current);
canTreat = false;
break;
}
}
if(canTreat==true) {
answer++;
if(m==current.id)return answer;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] waitingList = new int[n];
for( int i=0; i<n; i++ ) {
waitingList[i] = sc.nextInt();
}
System.out.print(T.solution(n, m, waitingList));
}
}
- 향상된 for문에선 큐에서 데이터를 빼내는 작업을 진행하지 않고 전하게 순회한다.
- Patient로 클래스를 따로 만들어 준 이유
- 각 환자가 가지고 있는 정보로는 환자의 대기 번호와 위험도가 주어지고, 이 정보를 하나로 묶어서 효과적으로 관리하고자 했다. 이런 상황에서 객체 지향 프로그래밍의 개념을 활용하여 Patient 클래스를 만들면 코드가 더 명확하고 구조적으로 표현된다.