출처 : 백준 #5430
시간 제한 | 메모리 제한 |
---|---|
1초 | 256MB |
선영이는 주말에 할 일이 없어서 새로운 언어 AC를 만들었다. AC는 정수 배열에 연산을 하기 위해 만든 언어이다. 이 언어에는 두 가지 함수 R(뒤집기)과 D(버리기)가 있다.
함수 R은 배열에 있는 숫자의 순서를 뒤집는 함수이고, D는 첫 번째 숫자를 버리는 함수이다. 배열이 비어있는데 D를 사용한 경우에는 에러가 발생한다.
함수는 조합해서 한 번에 사용할 수 있다. 예를 들어, "AB"는 A를 수행한 다음에 바로 이어서 B를 수행하는 함수이다. 예를 들어, "RDD"는 배열을 뒤집은 다음 처음 두 숫자를 버리는 함수이다.
배열의 초기값과 수행할 함수가 주어졌을 때, 최종 결과를 구하는 프로그램을 작성하시오.
첫째 줄에 테스트 케이스의 개수 T가 주어진다. T는 최대 100이다.
각 테스트 케이스의 첫째 줄에는 수행할 함수 p가 주어진다. p의 길이는 1보다 크거나 같고, 100,000보다 작거나 같다.
다음 줄에는 배열에 들어있는 수의 개수 n이 주어진다. (0 ≤ n ≤ 100,000)
다음 줄에는 [x1,...,xn]과 같은 형태로 배열에 들어있는 수가 주어진다. (1 ≤ xi ≤ 100)
전체 테스트 케이스에 주어지는 p의 길이의 합과 n의 합은 70만을 넘지 않는다.
각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.
4
RDD
4
[1,2,3,4]
DD
1
[42]
RRD
6
[1,1,2,3,5,8]
D
0
[]
[2,1]
error
[1,2,3,5,8]
error
처음에는 명령어를 어떻게하면 짧게 줄일까 생각했었다.
O(N)
이 소요가 되어 결국 시간초과가 떴다.따라서 굳이 직접 뒤집지 않더라도 최종적으로 R의 개수가 홀수인지 짝수인지에 따라 뒤집을지 말지를 결정하여주면 된다.
그리고 D 명령어는 해당 명령어 실행시까지 나타난 R의 개수가 홀수인지 짝수인지에 따라 홀수면 앞에서 1개를 제거하면 되고, 짝수면 뒤에서 1개를 제거하면 된다.
front
, back
이라는 변수에 각각 모아 최종적으로 arr = arr[front:n-back]
이렇게 만들어주면 된다.마지막으로 리스트 자체를 출력하는 것이 아니라 띄어쓰기 없이 리스트를 출력해야하므로 solution
함수에서 마지막 for문이 들어갔다
# 백준 5430번 AC 문자열
from sys import stdin
input = stdin.readline
def solution(n, arr, command):
r_count = 0
front = 0
back = 0
for x in command:
if x == "R":
r_count += 1
else:
if r_count % 2 == 0:
front += 1
else:
back += 1
if front+back > n:
return "error"
else:
arr = arr[front:n-back]
if r_count % 2 != 0:
arr.reverse()
result = "["
for i in range(len(arr)):
result += str(arr[i])+","
result = result[:-1] + "]"
if len(result) == 1:
result = "[]"
return result
t = int(input())
answer = []
for i in range(t):
command = input().rstrip()
n = int(input())
temp = input().rstrip()
if len(temp) > 2:
arr = list(map(int, temp.strip("[]").split(",")))
else:
arr = []
answer.append(solution(n, arr, command))
for i in range(len(answer)):
print(answer[i])
# 백준 5430번 AC 문자열
from sys import stdin
from collections import deque
input = stdin.readline
def solution(n, arr, command):
temp = ""
count = 1
for x in range(len(command)-1):
if command[x] == command[x+1]:
count += 1
else:
temp += str(count) + command[x]
count = 1
temp += str(count) + command[-1]
command = temp
tempCount = ""
for x in command:
if x != "R" and x !="D":
tempCount += x
else:
number = int(tempCount)
tempCount = ""
if x == "R":
if number % 2 == 0 :
continue
else:
arr.reverse()
else:
if number > n:
return "error"
else:
if number == 1:
arr.popleft()
else:
arr = list(arr)[number:]
n -= number
arr = deque(arr)
return list(arr)
t = int(input())
answer = []
for i in range(t):
command = input().rstrip()
n = int(input())
temp = input().rstrip()
if len(temp) > 2:
arr = deque(map(int, temp.strip("[]").split(",")))
else:
arr = []
answer.append(solution(n, arr, command))
for i in range(len(answer)):
print(answer[i])