https://www.acmicpc.net/problem/1966
1966번: 프린터 큐
여러분도 알다시피 여러분의 프린터 기기는 여러분이 인쇄하고자 하는 문서를 인쇄 명령을 받은 ‘순서대로’, 즉 먼저 요청된 것을 먼저 인쇄한다. 여러 개의 문서가 쌓인다면 Queue 자료구조에
www.acmicpc.net
이 문제는 큐를 사용하였다.
이때, 배열에 우선순위를 넣고, 입력이 끝나면 정렬하여 앞에서부터 꺼내 사용했다.
큐에 넣을 요소는 구조체를 생성하여 우선 순위와 입력 순서를 저장할 수 있도록 하였다.
알고리즘으로는 큐의 앞에서부터 꺼내되, 요소의 우선순위가 배열에서 꺼낸 max 값보다 낮으면 다시 삽입하고
max값에 해당하면 max 값을 그 다음 순위로 갱신하고, 배열의 범위를 벗어나지 않는 조건하에 반복을 이어 갔다.
반복문의 조건으로는 원하는 입력 순서를 찾게되면 멈추게 하였다.
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
typedef struct Element {
int priority;
int value;
} Element;
bool bigger(int a, int b) {
if (a > b) return true;
else return false;
}
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
queue<Element> q;
vector<int> p;
int N, M;
cin >> N >> M;
for (int j = 0; j < N; j++) {
int input;
cin >> input;
Element e;
e.priority = input;
e.value = j;
q.push(e);
p.push_back(input);
}
sort(p.begin(), p.end(), bigger);
int maxIndex = 0;
int max = p[maxIndex];
int find = -1;
int count = 0;
while (M != find) {
Element e = q.front();
q.pop();
if (e.priority < max) {
q.push(e);
}
else {
count += 1;
find = e.value;
maxIndex += 1;
if (maxIndex < p.size())
max = p[maxIndex];
else
break;
}
}
cout << count << '\n';
}
}
'Baekjoon Review' 카테고리의 다른 글
[Silver 3] 2108번 통계학 (0) | 2023.10.11 |
---|---|
[Silver 5] 2751번 수 정렬하기 2 (0) | 2023.10.10 |
[Silver 3] 1929번 소수 구하기 (0) | 2023.10.10 |
[Silver 4] 1920번 수 찾기 (0) | 2023.10.05 |
[Silver 2] 1874번 스택 수열 (0) | 2023.10.05 |