[백준 5430] AC

3-3

구현을 완료했지만 시간 복잡도가 높아 시간초과가 나온다.

reverse와 pop의 시간복잡도가 O(n)이므로 pop때문에 이러한 문제가 발생하는것 같다.

따라서 pop을 deque를 사용하여 popleft로 시간복잡도를 O(1)로 낮추지만 시간초과는 해결되지 않았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from sys import stdin
from collections import deque
def solution(command,l):
if len(l)<command.count('D'):
return 'error'
for c in command:
if c=="R":
l.reverse()
elif c=="D":
l.popleft()
return '['+','.join(l)+']'


T = int(input())
ans = []
for _ in range(T):
command = stdin.readline()
n = int(stdin.readline().rstrip())
l = deque(stdin.readline().rstrip()[1:-1].split(','))
if n==0:
l = []
print(solution(command,l))

따라서 R일때마다 뒤집지 않고, point 변수를 만들어주어 reverse일때마다 point변수를 바꾸어주고 pop은 reverse 마다 방향을 바꾸어 주어 pop을 해주는 방식으로 구현하였다.

예를 들어 reverse 할때마다 point값을 바꾸어주며 D일때 point값을 확인해 popleft할지 pop할지를 결정한다.

최종적으로 point의 값을 확인하여 reverse를 할지 말지 결정해준다.

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
from sys import stdin
from collections import deque
def solution(command,l):
point = 'left'
if len(l)<command.count('D'):
return 'error'
for c in command:
if c=="R":
if point =='left':
point ='right'
else:
point = 'left'
elif c=="D":
if point =='left':
l.popleft()
else:
l.pop()
if point =='left':
return '['+','.join(l)+']'
else:
l.reverse()
return '['+','.join(l)+']'


T = int(input())
ans = []
for _ in range(T):
command = stdin.readline()
n = int(stdin.readline().rstrip())
l = deque(stdin.readline().rstrip()[1:-1].split(','))
if n==0:
l = []
print(solution(command,l))

해결이 되었다!!

무조건 문제의 조건을 구현하기 보다는 보다 효율적인 방법을 찾는것이 바람직 하다는것을 느꼈다.

Author

jo-member

Posted on

2021-01-02

Updated on

2021-04-22

Licensed under

Comments