Koala - 5기/기초 알고리즘 스터디

<3주차> [BOJ / C++] 1874번 - 스택 수열

거북이목 2022. 1. 29. 12:14

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

 

 

문제

 

 

코드

#include <bits/stdc++.h>
using namespace std;
#include <cmath>
#define PI 3.141592653589793
#define ll long long


int main(void)
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    
    stack<int> s;
    string c;
    int n;
    cin >> n;
    int flag=1;
    for (int i=0; i<n; i++)
    {
        int x;
        cin >> x;
        while (x >= flag)
        {
            s.push(flag);
            flag++;
            c.push_back('+');
        }
        if (s.top() == x)
        {
            s.pop();
            c.push_back('-');
        }
        else
        {
            cout << "NO";
            return 0;
        }
    }

    for (int i=0; i<c.length(); i++)
    {
        cout << c[i] << '\n';
    }
}

 

 

풀이

입력받은 x와 flag를 비교하여 flag가 x와 같아질 때 까지, 스택s에 flag를 넣어주고 flag를 1증가시킨다.

그리고 string c에 '+'를 넣어준다.

 

이후 스택s의 top과 x가 같은지 확인하여 같다면, pop을 해주고 string c에 '-'를 넣어준다.

만약 다르다면, "NO"를 출력하고 종료시킨다.

 

마지막으로, string c를 반복문을 통해 출력한다.

 

 

결과

 

댓글수0