BOJ 문제풀이

백준 1874번 c++ 풀이

koreasunoo 2021. 8. 11. 20:49

안녕하세요 오늘은 스택을 이용하여 스택 수열이라는 문제를 풀어보도록 하겠습니다.

 

전략:

1. int 타입의 스택 s, string타입의 변수 result를 선언해준다.

2. 입력받은 n번만큼 반복하게 while문을 설정해주고 각 반복마다 x변수를 받아준다.

3. while(n--) 전에 cnt변수를 1로 선언해준다. 그 뒤, while(cnt<=x)를 통하여 1부터 x까지 숫자를 push해준다.

4. 만약 스택의 맨 위가 x이면 s.pop()을 해주고, 만약 아니면 비정상적인 접근이므로 result에 "NO"를 대입한후, while 문을 끝낸다.

코드:

#include <bits/stdc++.h>
using namespace std;
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	int n;
	cin>>n;
	stack<int> s;
	string result = "";
	int cnt = 1;
	while(n--){
		int x;
		cin>>x;
	 	while(cnt<=x){
			s.push(cnt);
			result+="+\n";
			cnt++;
			
		}
		if(s.top()==x){
			result+="-\n";
			s.pop();
		}
		else{
			result = "NO";
			break;
		}
	}
	cout<<result;
}

'BOJ 문제풀이' 카테고리의 다른 글

백준 4949번 c++ 풀이  (0) 2021.08.12
백준 2805번 c++ 풀이  (0) 2021.08.11
백준 1654번 c++ 풀이 (복습필요)  (0) 2021.08.10
백준 15829 c++ 풀이  (0) 2021.08.07
백준 9012번 c++ 풀이  (0) 2021.08.07