본문 바로가기

문제 풀이/문제 풀이(프로그래머스)

연습문제 > 택배상자

문제 위치 : https://school.programmers.co.kr/learn/courses/30/lessons/131704

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

스택을 사용하는 문제이다.

order에 해당하는 상자가 나올 때까지 벨트에서 꺼내며 그 동안의 상자는 보조벨트 스택에 쌓도록 처리한다.

이후 보조 벨트 스택에서 해당하는 상자를 꺼낼 수 있다면 꺼내고 그럴 수 없다면 종료하는 방식으로 구현하였다.

#include <vector>
#include <stack>

using namespace std;

int solution(vector<int> order) {
    int answer = 0;
    int box_num = 1;
    stack<int> support;

    for (int target : order) {
        while (box_num <= target) {
            support.push(box_num);
            box_num++;
        }
        if (!support.empty() && support.top() == target) {
            support.pop();
            answer++;
        } else {
            break;
        }
    }

    return answer;
}