본문 바로가기
C++ 코딩 문제 풀이/프로그래머스

[Programmers] 프로세스

by 섬댕이 2023. 12. 2.

 

 

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 


 

문제 해결 과정

착안

우선순위 큐(priority queue) 자료 구조나 큐(queue) 자료 구조를 이용하면 아래와 같은 어려운 점이 있으므로, std::vector<> 클래스를 활용하여 문제에서 주어진 동작을 구현하고자 하였다.

  • 우선순위 큐: 우선순위에 따라 인출되는 프로세스가 본래 몇 번째 프로세스였는지 찾는 과정이 복잡하다
  • 큐: 우선순위가 가장 높은 프로세스가 무엇인지 찾는 과정이 복잡하다

 

구현

가장 먼저 배열 내의 요소를 순차 탐색하여 우선순위가 최대인 프로세스의 우선순위 값을 구한 다음, std::vector<> 클래스의 erase() 및 push_back() 메서드를 활용하여 프로세스를 인출하거나 뒤쪽에 다시 추가하는 과정을 먼저 구현하고 테스트하였다.

 

이후 프로세스가 인출되거나 뒤쪽에 추가될 때, 매개변수 location으로 주어지는 프로세스의 위치가 동작에 맞게 갱신되도록 구현하고, 현재 배열에 남아있는 프로세스 중 가장 앞의 프로세스가 최대 프로세스이면서 location 값이 0인 경우에 결과를 반환하고 실행을 종료하도록 구현하였다.

 

[스포 주의] 아래 '더보기'를 누르면 코드가 나오니 주의하세요~

더보기
#include <vector>

using namespace std;

int solution(vector<int> priorities, int location)
{
    int answer = 0;
    int tgt_priority = priorities[location];
    int max_priority = 0;
    
    while (true)
    {
        if (max_priority == 0)
            for (int n : priorities)
                if (max_priority < n)
                    max_priority = n;

        int front = priorities[0];
        priorities.erase(priorities.begin());
        if (front == max_priority)
        {
            answer++;
            if (location == 0)
                break;
            
            max_priority = 0;
        }
        else
            priorities.push_back(front);
        
        if (--location < 0)
            location += priorities.size();
    }
        
    return answer;
}

 

실행 결과

'C++ 코딩 문제 풀이 > 프로그래머스' 카테고리의 다른 글

[Programmers] 귤 고르기  (0) 2023.12.06
[Programmers] 카펫  (2) 2023.12.05
[Programmers] 튜플  (0) 2023.09.25
[Programmers] 괄호 회전하기  (0) 2023.09.07
[Programmers] 호텔 대실  (0) 2023.09.07

댓글