알고리즘

C++ 알고리즘 - 백준 1874 스택 수열

마루설아 2024. 12. 15. 01:34

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

 

#include <iostream>
#include <stack>
using namespace std;

int main(void) {
	// C++ Init
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	int in1;
	int in2[100000] = { 0 };
	string str;

	stack<int> st;

	cin >> in1;

	for (int i = 0; i < in1; i++) {
		cin >> in2[i];
	}

	int i = 0;
	int j = 1;
	while (true) {
		if (j > in1 + 1) {
			cout << "NO";
			return 0;
		}

		if (i == in1) {
			int len = str.length();
			for (int i = 0; i < len; i++) {
				cout << str[i];
			}
			return 0;
		}
		
		if (in2[i] != j) {
			if (!st.empty() && st.top() == in2[i]) {
				str += "-\n"; st.pop();
				i++;
			}

			else {
				st.push(j); str += "+\n";
				j++;
				continue;
			}
		}

		else {
			st.push(j); str += "+\n";
			st.pop(); str += "-\n";
			i++;
			j++;
			continue;
		}
	}
}