프린터 관련 문제는 스택/큐의 대표적인 문제로 지난 번에 제대로 풀지 못했던 OMR 문제와 유사한 느낌이었다. 구조체를 만들어서 비교하는 느낌이 유사?!
stack과 que를 c++에 사용하는 방법이 익숙지 않아
https://youtu.be/dFjgHCLRUIs 링크의 "개발자로 취직하기" 분의 코드를 참고하였다.
구조체를 이용한다는 점에서부터 막혔던.....
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm> // 이건 이제 *max_element를 찾기 위해서 하는 것.
using namespace std;
// 구조체를 형성해서 queue만들기. 구조체를 queue의 형식으로 넣어주는 방법으로 구성한다.
struct PrintJob {
int priority;
int location;
};
int solution(vector<int> priorities, int location) {
queue<PrintJob> printer;
int turn = 0;
for (int i = 0; i < priorities.size(); i++) {
PrintJob job;
job.location = i;
job.priority = priorities[i];
printer.push(job);
}
while (!printer.empty()) {
// Job을 또 써도 뇌는게 지역 변수라 또 써도 앞에 것이랑 겹치지 않음.
// 2. 0 번을 꺼내서 max priority 아니면 다시 끝에 넣는다.
PrintJob job = printer.front(); // 벡터의 첫 번째 요소를 반환한다. front는 앞에 값 반환, back은 뒤에 값 반환. begin는 첫 번째 요소 가리킴. end는 마지막 요소 가리킴.
printer.pop(); // 빼서 비교하고
if (job.priority < *max_element(priorities.begin(), priorities.end())) {
printer.push(job);
}
else
{
turn++;
// 3. max priority가 맞다면 내가 찾는 job인지를 확인한다.
if (job.location == location)
break; // 내가 찾는 것이 같다면 나오면 됨.
priorities[job.location] = 0;
}
}
return turn;
}
int main(void) {
vector<int> priorities = { 2, 1, 3, 2 };
cout << solution(priorities, 2);
return 0;
}'코딩 테스트 공부 > C++' 카테고리의 다른 글
| [Week18-6, Day124, 퇴고] 주말인 토요일 시작, 개인 공부하기 (0) | 2022.06.18 |
|---|