알고리즘 공부

[BOJ] AC(5450) 문제 풀기 | Python3

유나쒸 2021. 4. 21. 07:14


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from collections import deque
 
result=[]
 
for _ in range(int(input())):
    function=input(); n=int(input())
    # RR 연속한 경우 두번 뒤집기=원상태 이므로 처리할 필요가 없어 지움
    function=function.replace('RR','')
    
    # 원소 없는 경우 빈 리스트 처리
    if(n==0): input(); ary=[]
    # 문자열 '[1,2,3]' 입력을 리스트 [1,2,3] 형태로 변환 
    else: ary=list(map(int, input().strip('[]').split(',')))
    # 리스트 -> deque 변환
    queue=deque(ary)
 
    # 함수 조합에서 'D' 개수 반환
    cntD=function.count('D')
    # 원소 개수보다 삭제하는 D 함수가 많으면 error 
    if n < cntD: result.append('error')
    # 원소 개수와 삭제하는 D 함수 개수 같으면 빈 리스트
    # n=0이고 함수 조합에 D 함수 개수=0 이면 빈 리스트
    elif n==cntD: result.append('[]')
 
    else:
        reverse=False
        for func in function:
            # R 함수일 때 일일이 리스트를 뒤집는 대신 boolean 변수로 check
            if func=='R': reverse=not reverse
            else# func=='D'
                # reverse=True: R함수 개수가 홀수번째일 때 R함수 적용해야하므로 맨 뒤의 원소 제거
                if reverse: queue.pop()
                # reverse=False: R함수 개수가 짝수번째일 때 R함수 적용안해야하므로 맨 앞의 원소 제거
                else: queue.popleft()
        # reverse=True 이면 최종 R함수 개수가 홀수이므로 뒤집어야하니까 최종 출력을 위해 리스트 뒤집기 
        if reverse : queue.reverse()
        # 출력형식 '[1,2,3'] 이므로 변환
        result.append('['+','.join(list(map(str, list(queue))))+']')
        
print(*result, sep='\n')
 
cs