백준

백준 1874번 C++

solfa 2023. 11. 15. 20:58

https://www.acmicpc.net/problem/1874

 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

 

생각
1. 1~n까지 push 시킨다 ( s에 들어가야할 수를 i, i<t[k]까지 s에 i를 푸쉬해줌)
2. s.top == 같다면!! pop 해주기
 + NO가 나오는 조건 : 다음 출력을 할 때 앞에 수에 의해 막힐 때!

 

문제 이해가 안돼서 오래걸렸다...

생각보다 구현하거나 조건 걸어야 할 건 많이 없었다!

 

문제 이해에 도움을 준 글 : https://organize-study.tistory.com/60

 

#include <iostream>
#include <stack>

using namespace std;

stack<int> s;

int main()
{
    int N, num, cnt = 1;
    cin >> N;
    string result;

    for (int i = 0; i < N; i++)
    {
        cin >> num;
        while (cnt <= num)
        {
            s.push(cnt++);
            result += "+\n";
        }

        if (s.top() == num)
        {
            s.pop();
            result += "-\n";
        }
        else
        {
            cout << "NO\n";
            return 0;
        }
    }
    
    cout << result;
    return 0;
}
728x90

'백준' 카테고리의 다른 글

백준 1018 C++  (0) 2023.11.18
백준 9093 C++  (1) 2023.11.16
백준 2805번 C++  (0) 2023.11.15
백준 2667 c++ 런타임 에러 (OutOfBounds)  (0) 2023.08.25
백준 2644번 c++  (0) 2023.08.09