[baekjoon] 1874 스택 수열 만들기

윤주원·2025년 4월 3일
0

baekjoon

목록 보기
12/14
post-thumbnail

문제 링크 : https://www.acmicpc.net/problem/1874

  • 처음 답
#include <vector>
#include <iostream>
#include <stack>

using namespace std;

int main(){
    stack<int> st;
    int n,a,cnt = 1;
    cin >> n;
    vector<string> arr;

    for(int i=0;i<n;i++){
        cin >> a;
       
        while(cnt<=a){
            st.push(cnt);
            cnt++;
            arr.push_back("+");
        }
    
            if(st.top() == a){
                st.pop();
                arr.push_back("-");
            }
            else{
                cout << "NO";
                return 0;
            }
       
    }
    for(auto &a : arr)
        cout << a << endl;

}
  • 출력이 되는 것을 확인 후, 제출했지만 시간 초과가 발생했다.
  • 이를 해결하기 위해 더 빠른 입력을 사용했다.
  ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
  • 위 내용을 main 제일 처음 사용하여 C 스타일 입출력과의 동기화를 끊고,
    cin / cout이 훨씬 빨라지게 했다.
  • 그러나 여전히 시간 초과가 발생했다.

마지막 해결 방법

  • endl을 "\n"으로 변경!!!
  • endl은 줄바꿈을 하면서 출력을 flush(강제 출력)까지 하니까 느려진다.
  • 그래서 반복문에서 endl을 많이 쓰면 느려진다.
profile
안녕하세요

0개의 댓글