[백준] 1874 스택 수열
#include <vector>
#include<stack>
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int n;
cin >> n;
vector<int> vec;
for (int i = 0; i < n; ++i) {
int input;
cin >> input;
vec.push_back(input);
}
int num = 1;
stack <int> st;
int idx = 0;
bool possible = true;
vector<char> output;
while (idx < n) {
while (st.empty() || st.top() < vec[idx]) {
if (num > n) break;
st.push(num);
num++;
output.push_back('+');
}
if (st.top() == vec[idx]) {
st.pop();
idx++;
output.push_back('-');
}
else {
possible = false;
break;
}
}
if (possible) {
for (int i = 0; i < output.size(); ++i) {
cout << output[i] << "\n";
}
}
else cout << "NO";
return 0;
}
1년 전 코드
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
stack<int> s;
vector<char> res;
int num = 1;
for (int i = 0; i < n; ++i) {
int input;
cin >> input;
if (s.empty()) {
s.push(num);
res.push_back('+');
num++;
}
if (input < s.top()) {
cout << "NO";
return 0;
}
while (input > s.top()) {
s.push(num);
res.push_back('+');
num++;
}
if (input == s.top()) {
s.pop();
res.push_back('-');
}
}
for (int i = 0; i < res.size(); ++i)
cout << res[i] << "\n";
return 0;
}