본문으로 바로가기

(Python) 백준 5430 / AC

category Coding Test Practice/python 2024. 7. 12. 22:15
import sys
from collections import deque

input = sys.stdin.readline

total = int(input())

# D는 1, R은 2로 해서 페어를 만들어 리스트를 구현 [D 또는 R, D 또는 R의 개수]
# ex) DDRRRDDDR이면
# [[1, 2], [2, 3], [1, 3], [2, 1]]
def compress_string(s):
    if not s:
        return []
    
    s = s.strip()  # 문자열의 앞뒤 공백 문자를 제거

    compressed = []
    current_char = s[0]
    count = 1

    for char in s[1:]:
        if char == current_char:
            count += 1
        else:
            compressed.append([1 if current_char == 'D' else 2, count])
            current_char = char
            count = 1

    compressed.append([1 if current_char == 'D' else 2, count])
    return compressed

for _ in range(total):
    cmd = str(input())
    # D는 1, R은 2
    cmdL = compress_string(cmd)
    list_count = int(input())
    num_list = eval(str(input()))
    # 뒤집히지 않은 초기상태 ==> False
    checkL = False
    
    # D의 개수가 리스트 요소보다 많으면 error 처리
    if (list_count < cmd.count('D')):
        print('error')
        continue
    
    # 페어를 빼면서 처리해줌
    while cmdL:
    	# error가 아니면서 리스트가 비면 바로 print
        if len(num_list) == 0:
            # print("[]")
            break
        
        # R의 개수에 따라 앞에서 뺄지 뒤에서 뺄지 정함
        if (cmdL[0][0] == 1):
        	# R이 홀수면 뒤집힌 상태 ==> 뒤에서 D의 개수만큼 pop
            if checkL:
                for _ in range(cmdL[0][1]):
                    num_list.pop()
            # R이 짝수면 그냥 그대로의 상태임
            else:
                for _ in range(cmdL[0][1]):
                    num_list.pop(0)
            
        elif (cmdL[0][0] == 2):
        	# R이 홀수개면 홀수처리
            if ((checkL == False) and (cmdL[0][1] % 2 == 1)):
                checkL = True
            # R이 짝수개면 짝수처리
            elif ((checkL == True) and (cmdL[0][1] % 2 == 1)):
                checkL = False
        # 페어를 빼줌
        cmdL.pop(0)
    # R이 최종적으로 홀수개면 뒤집어줌
    if checkL:
        num_list = num_list[::-1]
    # 공백제거
    print(str(num_list).replace(" ", ""))