Study/Algorithm
프로그래머스 (C/C++) 131704 : 택배상자
hwooo
2024. 5. 10. 14:46
https://school.programmers.co.kr/learn/courses/30/lessons/131704


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


풀이
스택을 사용하여 컨테이너의 박스들을 확인했다.
주컨테이너는 한 번 박스를 빼면 다시 넣지 못하는 점에 유의해야 한다.
코드
#include <stack>
using namespace std;
int solution(vector<int> order) {
stack<int> primary, secondary;
int ans = 0;
for (int i = order.size(); i >= 1; i--)
primary.push(i);
while (ans < order.size()) {
// 보조컨테이너 확인
if (secondary.size() && secondary.top() == order[ans]) {
ans++;
secondary.pop();
continue;
}
// 주 -> 보조로 옮기며 확인
while (primary.size() && primary.top() != order[ans]) {
secondary.push(primary.top());
primary.pop();
}
// 주 컨테이너에서 꺼내기
if (primary.size()) {
primary.pop();
ans++;
}
else
return ans;
}
return ans;
}