GitHubSeob
C++ / 백준 / 5430 / AC 본문
문제
https://www.acmicpc.net/problem/5430
5430번: AC
각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.
www.acmicpc.net
문제풀이
'R'을 입력받을 때 마다 reverse를 하면 시간초과가 난다.
'D'를 입력받을때 마다 vector.erase로 지웠더니 시간초과가 난다.
deque를 사용하지 않고 시작 인덱스인 start, 끝 인덱스인 end를 이용하여 풀었다.
getline과 istringstream으로 쉼표로 구분하여 string을 자르고 int형 vector에 입력한다.
rev라는 변수를 두어 'R'을 입력받으면 * -1을 하여 거꾸로 됐는지, 정상적으로 됐는지를 체크한다.
rev == 1이라면 start를 +1 하여 앞 부분을 지운것처럼 한다.
rev == -1이라면 end를 -1 하여 뒷부분을 지운것처럼 한다.
반복문이 다 실행됐으면
start > end라면 에러가 나야하므로 error을 출력,
start == end라면 "[]"만 출력,
그 외에는 rev값에 따라 start부터 end-1까지 출력 또는,
end-1부터 start까지 출력하면 된다.
숫자를 입력받지 않고 R만 입력받았을때 괄호만 출력하는 것을 몰라서 반례를 찾아 고쳤더니 됐다.
(start == end 부분)
1
R
0
[]
코드
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int T(0), idx(0), n(0);
int cnt(0);
string p(""), num("");
string str("");
cin >> T;
while (T--) {
int start(0), end(0);
int rev(1);
vector<int>arr;
cin >> p >> n;
cin >> num;
num.erase(0, 1);
num.erase(num.size() - 1, 1);
istringstream istr(num);
while (getline(istr, str, ',')) {
arr.push_back(stoi(str));
end++;
}
for (idx = 0; idx < p.size(); ++idx) {
if (p[idx] == 'R') {
rev *= -1;
}
else {
if (rev == 1) {
++start;
}
else {
--end;
}
}
}
if (start > end) {
cout << "error\n";
}
else if (start == end)
cout << "[]\n";
else {
cout << '[';
if (rev == 1) {
for (idx = start; idx + 1 < end; ++idx) {
cout << arr[idx] << ',';
}
cout << arr[idx];
}
else {
for (idx = end - 1; idx > start; --idx) {
cout << arr[idx] << ',';
}
cout << arr[idx];
}
cout << "]\n";
}
}
}
'Baekjoon > Gold' 카테고리의 다른 글
C++ / 백준 / 1016 / 제곱 ㄴㄴ 수 (0) | 2023.06.07 |
---|---|
C++ / 백준 / 9663 / N-Queen (1) | 2023.06.06 |
C++ / 백준 / 21942 / 부품 대여장 (0) | 2022.04.12 |
C++ / 백준 / 2696 / 중앙값 구하기 (0) | 2022.04.12 |
C++ / 백준 / 21939 / 문제 추첨 시스템 Version 1 (0) | 2022.04.07 |