728x90
스택 문제입니다.
스택의 push와 pop을 이용해서 입력된 배열의 모양을 만들 수 있는지 찾아야합니다.
stack에 쌓이는 수는 1부터 n까지 차례대로 쌓입니다. (1부터 n = num)
비어있거나, top()이 현재 찾는 수와 다르면
num을 push해줍니다.
top()이 찾는 수와 같으면 pop()을 해줍니다.
num이 n보다 커지면 만들 수 없는 배열이 됩니다.
#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
int n;
int arr[100010];
stack<int> s;
vector<char> v;
int num;
int main(int argc, char *argv[])
{
num = 1;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf(" %d", &arr[i]);
}
for (int i = 0; i < n; ++i) {
if (s.empty() || s.top() != arr[i]) {
while (1) {
if (num > n) {
puts("NO");
return 0;
}
s.push(num++);
v.push_back('+');
if (s.top() == arr[i]) {
s.pop();
v.push_back('-');
break;
}
}
}
else if (s.top() == arr[i]) {
s.pop();
v.push_back('-');
}
}
for (int i = 0; i < v.size(); i++) {
printf("%c\n", v[i]);
}
return 0;
}
'알고리즘' 카테고리의 다른 글
[C++] 백준 10845번 큐 (0) | 2019.09.07 |
---|---|
[C++] 백준 17298번 오큰수 (2) | 2019.09.05 |
[C++] 백준 4949번 균형잡힌 세상 (0) | 2019.09.04 |
[C++] 백준 9012번 괄호 (0) | 2019.09.04 |
[C++] 백준 2164번 카드2 (0) | 2019.09.04 |