-
[프로그래머스/Level 2] 프린터 (C++)알고리즘 문제풀이/프로그래머스 2020. 11. 1. 15:51
programmers.co.kr/learn/courses/30/lessons/42587
코딩테스트 연습 - 프린터
일반적인 프린터는 인쇄 요청이 들어온 순서대로 인쇄합니다. 그렇기 때문에 중요한 문서가 나중에 인쇄될 수 있습니다. 이런 문제를 보완하기 위해 중요도가 높은 문서를 먼저 인쇄하는 프린
programmers.co.kr
1. 중요도, 대기 목록 위치를 담을 pair형 벡터 print 선언
2. 우선순위를 내림차순으로 정렬하고, 큐에다가 push
3. 처음을 가리키는 idx를 선언하고, print[idx]의 first값과 큐의 front 값을 비교
- print[idx].first < q.front() 라면 현재 print 원소를 tmp에 저장하고 삭제, 그리고 tmp를 맨 뒤에 삽입
- print[idx].first == q.front() 라면 idx값을 증가하고, q를 pop
4. q가 텅 비면, 정렬된 print 벡터에서 print의 second 값이 location과 같아지는 인덱스를 찾고, +1을 해서 리턴#include <string> #include <vector> #include <queue> #include <functional> // greater<>() : 내림차순, less<>() : 오름차순 #include <algorithm> using namespace std; int solution(vector<int> priorities, int location) { vector<pair<int, int> > print; for(int i=0;i<priorities.size();i++) { print.push_back({priorities[i],i}); } sort(priorities.begin(),priorities.end(),greater<>()); queue<int> q; for(int i=0;i<priorities.size();i++) { q.push(priorities[i]); } int idx=0; while(!q.empty()) { if(print[idx].first < q.front()) { auto tmp = print[idx]; print.erase(print.begin()+idx); print.push_back(tmp); } else if(print[idx].first == q.front()) { idx++; q.pop(); } } for(int i=0;i<print.size();i++) { if(print[i].second == location) { return i+1; } } }
#include <string> #include <vector> #include <queue> using namespace std; int solution(vector<int> priorities, int location) { int answer = 1; priority_queue<int, vector<int>, less<int> > pq; queue<pair<int, int> > q; for(int i = 0; i < priorities.size(); i++) { pq.push(priorities[i]); q.push({i, priorities[i]}); } while(!pq.empty()) { int maxx = pq.top(); int idx = q.front().first; int value = q.front().second; q.pop(); if(value < maxx) { q.push({idx, value}); } else { if(idx == location) { return answer; } pq.pop(); answer++; } } }
'알고리즘 문제풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Level 2] 카카오프렌즈 컬러링북 (C++) (0) 2020.11.03 [프로그래머스/Level 2] 가장 큰 수 (C++) (0) 2020.11.01 [프로그래머스/Level 2] 다리를 지나는 트럭 (C++) (0) 2020.11.01 [프로그래머스/SQL] String, Date (MySQL) (0) 2020.10.31 [프로그래머스/SQL] JOIN (MySQL) (0) 2020.10.31