No Rules Rules

스택 수열 (feat. 백준, 1874번) 본문

생활/코테

스택 수열 (feat. 백준, 1874번)

개발하는 완두콩 2022. 8. 12. 12:49
728x90
반응형

스택 수열
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

 

반응형

 

// woohyeon.kim
// kim519620.tistory.com
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
int main() {
	ios::sync_with_stdio(false), cin.tie(NULL);
	register int N;
	stack<int> ans;
	queue<int> tmp;
	vector<char> words;
	cin >> N;
	for (register int n = 0, v; n < N; ++n)
		cin >> v, tmp.push(v);
	register int index = 1;
	while (!tmp.empty()) {
		if (index > (N + 1))
			break;
		if (ans.empty() || ans.top() != tmp.front())
			ans.push(index++), words.push_back('+');
		else if (ans.top() == tmp.front())
			ans.pop(), tmp.pop(), words.push_back('-');
	}
	if (!ans.empty() || !tmp.empty())
		cout << "NO" << "\n";
	else
		for (auto& word : words)
			cout << word << "\n";
	return 0;
}
// *&)*@*
  1. 1부터 8까지 순서대로 스택에 push 또는 pop을 했을 경우, 문제로 주어진 순서대로 출력을 할 수 있는가 를 묻는 문제입니다.
  2. 따라서 순서대로 출력할 수 있다면 1부터 8을 저장한 공간이 비어야 정상입니다. (모든 push, pop 과정이 이루어지므로)
  3. 하지만 공간이 비어있지 않거나 8을 초과한 값까지 비교가 이루어진다면 스택 수열을 만들 수 없는 것이므로 'NO'를 출력합니다.
728x90
반응형

'생활 > 코테' 카테고리의 다른 글

큐 2 (feat. 백준, 18258번)  (0) 2022.08.12
오큰수 (feat. 백준, 17298번)  (0) 2022.08.12
균형잡힌 세상 (feat. 백준, 4949번)  (0) 2022.08.12
괄호 (feat. 백준, 9012번)  (0) 2022.08.11
제로 (feat. 백준, 10773번)  (0) 2022.08.11
Comments