본문 바로가기
PS/BOJ

[백준] 17298. 오큰수(c++)

by backend 개발자 지망생 2025. 2. 3.

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

초기화를 -1로 해주었다.

가변배열로 받으니 시간이 많이 소모되었다.. 

입력값이 stk.top보다 큰 값이 나왔을 때 stack에 있는 인덱스와 입력값을 대입해주면 된다.

역시 코테에서는 fill_n을 써야할지 싶다.

memset은 unsigned char로 두번째 인자로 받아주기 때문에 0 또는 null로만 받아주는 것이 좋다. 안그러면 쓰레기값을 경험할 수 있다..

 

 


 

#include<iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <climits>
#include <queue>
#include <set>
#include <cmath>
#include <stack>
#include <list>

using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int n;

    // 스택
    stack<pair<int, int> > stk;

    cin >> n;

    vector<int> arr(n + 1, -1); // 초기화하기 위해 가변배열 선언
    vector<int> answer(n + 1, -1); // 초기화하기 위해 가변배열 선언

    stk.push(make_pair(1087654321, 0));

    for (int i = 1; i <= n; i++) {
        cin >> arr[i];
        while (stk.top().first < arr[i]) {
            answer[stk.top().second] = arr[i];
            stk.pop();
        }
        stk.push(make_pair(arr[i], i));
    }

    for (int i = 1; i <= n; i++) {
        cout << answer[i] << " ";
    }

    return 0;
}