반응형
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
풀이 )
현재 입력된 값과 비교하면서 1부터 stack에 집어넣고, 출력을 위한 vector에 '+'를 넣는다.
현재 입력된 값과 stack의 top이 일치하면 pop하고, 출력을 위한 vector에 '-'를 넣는다.
이 후 stack이 비어있는 경우, 즉 수열을 만들 수 있는 경우 vector의 원소를 모두 출력하고,
비어있지 않은 경우 "NO"를 출력한다.
#include <iostream>
#include <vector>
using namespace std;
int main(void){
ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<char> vc;
vector<int> vi;
int vi_input = 1;
while(n--){
int seq;
cin >> seq;
while(vi_input<=seq){
vi.push_back(vi_input++);
vc.push_back('+');
}
if(vi.back() == seq){
vi.pop_back();
vc.push_back('-');
}
}
if(vi.empty()){
for(vector<char>::iterator it = vc.begin(); it != vc.end(); ++it)
cout << *it << '\n';
}
else
cout << "NO" << endl;
return 0;
}
주의 )
결과 출력 시 줄바꿈에 std::endl 사용 시 시간초과가 난다.
반응형
'문제풀이 > 백준' 카테고리의 다른 글
[C++] 백준 - 17144 : 미세먼지 안녕! (0) | 2020.12.07 |
---|---|
[C++] 백준 - 14499 : 주사위 굴리기 (0) | 2020.12.05 |
[C++] 백준 - 10773 : 제로 (0) | 2020.12.01 |
[C++] 백준 - 5430 : AC (0) | 2020.11.30 |
[C++] 백준 - 17300 : 패턴 (0) | 2020.11.29 |