[문제 풀이]
1. 번호표를 queue에 입력받습니다.
2. queue에서 front가 현재 들어갈 수 있는 번호표라면 간식을 받으러 보내줍니다.
3. queue에서 front가 현재 들어갈 수 없다면 stack이 비어있는지 체크하고 비어있다면 stack에 push 해줍니다.
4. stack이 비어있지 않다면 stack의 top을 체크하고 현재 들어갈 수 있는 번호표라면 간식을 받으러 보내줍니다.
5. stack의 top이 현재 들어갈 수 없다면 stack의 top이 queue의 front보다 작은지 체크하고 작다면 "Sad"를 출력하도록 합니다.
6. stack의 top이 queue의 front보다 크다면 stack에 push 해주고 1 - 6번 과정을 queue가 빌 때까지 반복합니다.
7. 마지막으로 queue가 빌때까지 동작하면 "Nice"를 출력합니다.
[코드]
1. 번호표를 queue에 입력받습니다.
int N, cnt = 1, flag = 0, tmp;
stack<int> st;
queue<int> q;
cin>>N;
for(int n=0; n<N; n++){
cin>>tmp;
q.push(tmp);
}
2. queue에서 front가 현재 들어갈 수 있는 번호표라면 간식을 받으러 보내줍니다.
if(cnt == q.front()){
q.pop();
cnt++;
continue;
}
3. queue에서 front가 현재 들어갈 수 없다면 stack이 비어있는지 체크하고 비어있다면 stack에 push 해줍니다.
if(st.empty()){
st.push(q.front());
q.pop();
continue;
}
4. stack이 비어있지 않다면 stack의 top을 체크하고 현재 들어갈 수 있는 번호표라면 간식을 받으러 보내줍니다.
if(st.top() == cnt){
st.pop();
cnt++;
continue;
}
5. stack의 top이 현재 들어갈 수 없다면 stack의 top이 queue의 front보다 작은지 체크하고 작다면 "Sad"를 출력하도록 합니다.
if(st.top() < q.front()){
flag = 1;
break;
}
6. stack의 top이 queue의 front보다 크다면 stack에 push 해주고 1 - 6번 과정을 queue가 빌 때까지 반복합니다.
else{
st.push(q.front());
q.pop();
}
7. 마지막으로 queue가 빌때까지 동작하면 "Nice"를 출력합니다.
if(flag == 1){
cout<<"Sad"<<"\n";
}else{
cout<<"Nice"<<"\n";
}
[전체 코드]
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N, cnt = 1, flag = 0, tmp;
stack<int> st;
queue<int> q;
cin>>N;
for(int n=0; n<N; n++){
cin>>tmp;
q.push(tmp);
}
while(!q.empty()) {
if(cnt == q.front()){
q.pop();
cnt++;
continue;
}
if(st.empty()){
st.push(q.front());
q.pop();
continue;
}
if(st.top() == cnt){
st.pop();
cnt++;
continue;
}
if(st.top() < q.front()){
flag = 1;
break;
}else{
st.push(q.front());
q.pop();
}
}
if(flag == 1){
cout<<"Sad"<<"\n";
}else{
cout<<"Nice"<<"\n";
}
}
https://www.acmicpc.net/problem/12789
'Algorithm > Baekjoon' 카테고리의 다른 글
[ 백준 1431 ] 시리얼 번호 (C++) (0) | 2025.02.10 |
---|---|
[ 백준 1388 ] 바닥 장식 (JAVA) (0) | 2025.01.31 |
[ 백준 17266 ] 어두운 굴다리 (JAVA) (1) | 2025.01.13 |
[ 백준 1937 ] 욕심쟁이 판다 (C++) (0) | 2024.12.30 |
[ 백준 5046 ] 전국 대학생 프로그래밍 대회 동아리 연합 (C++) (0) | 2024.12.13 |