[프로그래머스 Lv2] 프로세스

수민이슈·2023년 6월 20일
0

[C++] 코딩테스트

목록 보기
35/116
post-thumbnail

🖊️ 문제

https://school.programmers.co.kr/learn/courses/30/lessons/42587

🖊️ 1차 풀이

처음에는
아 큐 ㅋㅋ 하고 요즘 서버공부하고있어서 무지성 우선순위큐를 해버렸다
그냥 우선순위 큐 하나로 해결하려고..
근데 인덱스가 꼭 필요한 상황이다

문 제 를 좀 읽 으 렴 수 민 아 ! !

#include <string>
#include <vector>
#include <queue>
#include <map>
#include <iostream>

using namespace std;

struct Process
{
    int id;
    int priority;
    
    Process(int _id, int _priority) : id(_id), priority(_priority) {}
};

int solution(vector<int> priorities, int location) {
    int answer = 0;
    queue<Process> q;
    map<int, int> priorityList;
    
    for(int i = 0 ; i < priorities.size() ; i++) {
        q.push(Process(i, priorities[i]));
        priorityList[priorities[i]]++;
    }
      
    while(true) {
        Process value = q.front();
        q.pop();
        if (!priorityList.empty()){
            auto maxPriority = --priorityList.end();
            if (value.priority >= *maxPriority->first){
                --priorityList[*maxPriority];
                answer++;
                if (value.id == location)
                    break;
            }
            else
			    q.push(value);
            	
        }
        else {
        	answer++;
            if (value.id == location)
                break;
        }
        
    }
    return answer;
}

근데 또 바보같이...
우선순위를 어떻게 저장해야 하냐.. 고민고민..

처음에는 Set : 중복제거해주는걸 생각했는데
말이되는소리냐 진짜 ㅠ

안되는거 깨닫고 그러면.. 중복인애 개수를 세자! 하고 Map을 써버림
진짜 뇌가 어떻게 된건지 ..

여기서 뇌정지가 와버림

뇌가 안굴러감..

그래서 다른 사람의 풀이를 보고, 이해해서 끙차끙차 풀어봤다

🖊️ 2차 풀이

#include <string>
#include <vector>
#include <queue>

using namespace std;

int solution(vector<int> priorities, int location) {
    int answer = 0;
    queue<pair<int,int>> q;
    priority_queue<int> pq;
    
    for(int i= 0 ; i < priorities.size() ; i++) {
        q.push(make_pair(i, priorities[i]));
        pq.push(priorities[i]);
    }
    
    while(!q.empty()) {
        int id = q.front().first;
        int priority = q.front().second;
        if (priority == pq.top() && id == location) {
            answer++;
            break;
        }
        else if (priority == pq.top()) {
            pq.pop();
            q.pop();
            answer++;
        }
        else {
            q.pop();
            q.push(make_pair(id,priority));
        }
    }
    
    return answer;
}

해설

일단 자료구조는

  • queue<pair<int, int>> q
    : 저장위치(id)와 우선순위(priority)를 담은 pair들의 queue. 얘네로 로직 돌릴거임
  • priority_queue<int> pq
    : 우선순위를 담은 우선순위 큐 (ㅋㅋ)

우선순위큐에 우선순위들 (먼저 처리해야 할 것들)이 정렬되어 들어가있고,
q를 기준으로 팽팽 돌린다.

매 루프마다 front로 저장위치, 우선순위를 받아놓고
조건에 따라 수행해준다.


정말..
자료구조의 중요성
그리고 각 자료구조를 편히 사용할 수 있도록 메소드 잘 알아놓기... ㅠ.ㅠ
진이 빠진다
쉬운 문제라고 생각했는데.....

0개의 댓글