[C++] 백준 1874 : 스택 수열

Updated:

1 minute read

백준 1874번 문제를 풀어보았다.

image


1. 문제 설명

image

  • stack를 사용하여 푸는 문제.
  • 1~N까지 stack에 넣는다고 생각할 때 stack에 넣고 빼는 작업을 조절하여 입력된 수열을 만들 수 있는지 찾는 문제


2. 문제 풀이

2.1 사용 변수

int stack[100001] = { 0, };
  • stack
    • stack 역할을 하는 배열


2.2 Solution

  • 직전에 들어온 값보다 작거나 직전에 들어온 값과 stack의 top의 값보다 큰값이 들어와야만 가능한 수열임.
    • stack의 구조상 만들어지는 규칙


2.3 전체 코드

#include <iostream>
#include <stack>
#include <stdio.h>
using namespace std;

int main() {
	//stack<int>s;
	int arr[100001] = { 0, };
	int stack[100001] = { 0, };
	int N;

	/* input part*/
	scanf("%d", &N);
	int p_top = 0;
	int p = 0;

	for (int i = 0; i < N; i++) {
		scanf("%d", &arr[i]);
		if (p < arr[i]) {
			if (p_top > arr[i]) {
				printf("NO\n"); return 0;
			}
			p_top = arr[i];
		}
		p = arr[i];
	}

	/*output part*/
	int idx = 0;
	int ascend = 1;
	int pstack = 0;

	do {
		while (arr[idx] != stack[pstack]) { //+
			stack[++pstack] = ascend++;
			printf("+\n");
		}
		while (pstack && arr[idx] == stack[pstack]) { //-
			pstack--;
			idx++;
			printf("-\n");
		}
		
	} while (ascend<N+1||pstack > 0);

	return 0;
}


3. Review

stack 구조체를 썼다가 시간복잡성 때문에 배열로 바꿨는데 별 차이 없다.


4. 실패한 접근 방법

없음.

Leave a comment