Problem Solving
[Java] 응급실
luminous13
2022. 1. 19. 12:34
문제
풀이
'도착한 순서대로 진료를 받는다'를 통해 Queue를 이용한 문제를 알 수 있습니다.
코드
package 인프런.스택과큐.응급실.방법1;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Person {
int id;
int priority;
public Person(int id, int priority) {
this.id = id;
this.priority = priority;
}
}
public class Main {
int solution(int n, int m, int[] arr) {
int answer=0;
Queue<Person> q = new LinkedList<>();
for (int i=0; i<n; i++) { // 큐 설정
q.offer(new Person(i, arr[i]));
}
int count = 0;
while(!q.isEmpty()) {
Person temp = q.poll(); // 하나 꺼내서
for (Person x : q) { // 큐 안에 남아있는 사람들 순회
if (x.priority > temp.priority) {
q.offer(temp); // 진료받으면 안되니깐 넣어준다.
temp = null;
break; // 더 비교할 필요가 없으니깐
}
}
if (temp != null) { // 우선순위가 높은 사람이 없었으니깐 진료받아도 된다.
answer++;
if (temp.id == m)
return answer;
}
}
return answer; // 여기로 올 일은 없다. 즉 컴파일 에러 방지를 위해 작성한다.
}
public static void main(String[] args) {
Main T = new Main();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] arr = new int[n];
for (int i=0; i<n; i++) {
arr[i] = in.nextInt();
}
System.out.println(T.solution(n, m, arr));
}
}
느낀점
처음에 큐를 이용해야된다는 것은 알았다. 하지만 값이 같은 경우에 M번째 인것을 어떻게 구별해야되나라는 고민이 있었는데 객체를 활용해서 해결해야된다는 것을 배웠다. 관련있는 데이터가 여러개 있을 때 객체를 만들면 데이터를 묶을 수 있는 장점이 있다.