알고리즘/인프런(자바(Java) 알고리즘 문제풀이 입문
5-8 응급실(Queue)
person456
2024. 1. 9. 21:04
재미있게 풀었던 문제
** 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
import java.util.*;
import java.util.stream.Stream;
import java.io.*;
class Solution{
static int n,m,k;
static StringTokenizer st;
static StringBuilder sb;
static int[] arr;
static ArrayList<Integer> list;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
st = new StringTokenizer(br.readLine(), " ");
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine(), " ");
Queue<int[]> q = new LinkedList<>();
for(int i=0; i<n; i++) {
q.offer(new int[] {i, Integer.parseInt(st.nextToken())});
}
int cnt=0;
while(true) {
int[] now = q.poll();
int now_id = now[0];
int now_priority = now[1];
int size = q.size();
boolean check = false;
for(int i=0; i<size; i++) {
int[] next = q.poll();
int next_id = next[0];
int next_priority = next[1];
if(next_priority>now_priority) {
check=true;
}
q.offer(new int[] {next_id, next_priority});
}
if(check) {
q.offer(new int[] {now_id, now_priority});
}else {
cnt++;
if(now_id==m) {
break;
}
}
}
System.out.println(cnt);
br.close();
bw.close();
}
}
|
cs |
- Queue의 특성, FIFO(First-In First-Out)을 통해 q의 내부 데이터들을 비교하여 더 높은 우선순위가 있다면 다시 offer
- 동일한 중복값이 존재하기 떄문에, 1차원 배열 int[]를 사용하여 id와 priority를 같이 넣음.