설모의 기록

[백준 1966] 프린터 큐 본문

알고리즘

[백준 1966] 프린터 큐

HA_Kwon 2017. 12. 20. 15:46

이 문제는 큐를 이용하는 문제입니다. 우선순위가 높은 문서를 먼저 뽑고 그 다음 들어온 순서대로 문서를 프린트해 입력된 인덱스값의 문서가 몇 번째로 프린트되게 되는지를 구하는 문제입니다. 


푸는 방식

- linkedlist 에 우선순위 값을 전부 저장합니다. 

- 큐에 입력된 순서대로 우선순위를 저장합니다.

- 큐를 돌면서 getMax() 함수를 이용해 가장 높은 우선순위를 구하고, 그 값과 현재 가장 앞에 있는 문서의 우선순위 값과 같으면 pop, 아니면 다시 push 합니다. 이 때, 우선순위 값도 같고 구하려는 인덱스가 현재의 문서의 인덱스와 일치하면 인덱스를 출력하고 다음 테스트케이스로 넘어갑니다.


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.Queue; import java.util.StringTokenizer; class Document { int index, priority; Document (int index, int priority) { this.index = index; this.priority = priority; } } public class Main { static LinkedList<Integer> list = new LinkedList<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; Queue<Document> q = new LinkedList<>(); int testcaseCount = Integer.parseInt(br.readLine()); while (testcaseCount-- > 0) { q.clear(); list.clear(); st = new StringTokenizer(br.readLine()); int docCount = Integer.parseInt(st.nextToken()); int index = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); for (int i = 0; i < docCount; i++) { int priority = Integer.parseInt(st.nextToken()); q.offer(new Document(i, priority)); list.add(findIndex(priority), priority); } int count = 1; while (!q.isEmpty()) { int max = getMax(); Document d = q.poll(); if (d.priority == max) { if (d.index == index) { bw.write(count + "\n"); break; } count++; list.remove(list.indexOf(max)); continue; } q.offer(d); } } bw.flush(); } public static int findIndex (int priority) { int index = 0; for (int i = 0; i < list.size(); i++) { index++; if (list.get(i) > priority) break; } return (index == list.size() ? 0 : index); } public static int getMax () { int max = Integer.MIN_VALUE; for (int i = 0; i < list.size(); i++) { if (max < list.get(i)) max = list.get(i); } return max; } }


'알고리즘' 카테고리의 다른 글

[백준 11866] 조세퍼스 문제  (0) 2017.12.20
[백준 1260] DFS 와 BFS  (0) 2017.12.20
[백준 1753] 최단경로  (0) 2017.12.14
[백준 11559] Puyo Puyo  (0) 2017.12.11
[백준 2146] 다리만들기  (0) 2017.12.10
Comments