728x90
반응형

https://www.acmicpc.net/problem/5430

 

5430번: AC

각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.

www.acmicpc.net

VERSION 2.0

import sys
from collections import deque

T = int(sys.stdin.readline())

for t in range(T):
    p = str(sys.stdin.readline().rstrip())
    n = int(sys.stdin.readline())
    x = deque(sys.stdin.readline().rstrip()[1:-1].split(','))
    if n == 0:
        x= []
    flag = 0
    for i in p:

        if i == 'R':
            flag+=1
        else:
            if len(x)==0:
                print('error')
                break
            if flag%2 == 0:
                x.popleft()
            else:
                x.pop()
    else:
        if flag%2 == 1:
            print("[" + ",".join(map(str , reversed(x))) + "]")
        else:
            print("[" + ",".join(map(str , x)) + "]")

==> D일때 ERROR 출력 

 

VERSION 1.0

import sys
from collections import deque

T = int(sys.stdin.readline())
for _ in range(T):
    array = list((sys.stdin.readline().rstrip()))
    flag = 0
    n = int(sys.stdin.readline())
    queue = deque(sys.stdin.readline().rstrip()[1:-1].split(","))
    if n==0:
        queue = deque()
    for i in range(len(array)):
        if array[i]== 'R' :
            flag+=1
        elif array[i] =='D':
            if len(queue)>=1:
                if flag%2==0:
                    queue.popleft()
                else:
                    queue.pop()
            else:
                print('error')
                break
    else:
        if flag % 2 ==1:
            queue.reverse()
            print("[" + ",".join(queue) + "]")

        else:
            print("[" + ",".join(queue) + "]")

0. [] 빈 리스트에 대한 것도 고려해야하므로 queue = deque()로 초기화 시켜준다.

 

1. deque(sys.stdin.readline().rstrip()[1:-1].split(",") ==> 입력값으로 [1,2,3,4] 받았을때 덱(deque)에는 deque(1,2,3,4) 저장

 

 

 

2. RR이 2번연속일 경우 그대로이므로 ==> 계속해서 reverse 해줄 필요 없다. ==> flag로 R이 나오는 횟수 센다. 

 

==> IF문으로 D가 나오면 그때 FLAG를 활용하므로 연속해서 나오는 R에 대해서만 고려한다.

 

3. R이 연속해서 짝수로 나오면 덱(DEQUE)는 그대로 상태이므로 앞에꺼 POPLEFT() 

 

4. R이 연속해서 홀수로 나왔다면 덱(DEQUE)은 REVERSE 될 것이었으므로 POP()을 통해 뒤에까 삭제해준다.

 

5. FOR문으로 돌린뒤 ==> 'RRD' -> 3번 돌린뒤 ==> R이 연속해서 나온것이 홀수라면 QUEUE를 REVERSE 해준것을 출력해준다.

 

728x90
반응형

+ Recent posts