입력 | 출력 |
---|---|
3 1234 3412 1000 1 1 16 | LL L DDDD |
: bfs를 이용하여 1~4를 수행한다.
각각의 명령어 D, S, L, R를 어떻게 저장해야하나 했는데 달고 다니면 되는 거였다. 이전꺼에 명령어를 문자열로 붙여서 큐에 함께 넣으면 된다.
- 3,4번 자릿수 회전시키는 부분에서 문자열로 바꿔서 수행하고 format으로 4자리를 맞춰주니 시간초과가 난다.
- 왼쪽으로 이동 : 1000으로 나눈 나머지에 10을 곱해서 네자리를 만들고 1000으로 나눈 몫을 더한다.
- 오른쪽으로 이동 : 10으로 나눈 나머지에 1000을 곱해서 네자리를 만들고 10으로 나눈 몫을 더한다.
pypy로 제출하지 않으면 시간초과를 피할 수 없다.
from collections import deque
import sys
def bfs(visited, s, e):
visited[s] = 1
q = deque()
ans = ''
q.append((s, ans))
while q:
x, ans = q.popleft()
if x == e:
return ans
if 2*x > 9999:
nx = (2*x)%10000
if visited[nx] == 0:
visited[nx] = 1
q.append((nx, ans+'D'))
if x==0 and visited[9999] == 0:
visited[9999] = 1
q.append((9999, ans+'S'))
if 2*x <= 9999 and visited[2*x] == 0:
visited[2*x] = 1
q.append((2*x, ans+'D'))
if 0<=x-1<10000 and visited[x-1] == 0:
visited[x-1] = 1
q.append((x-1, ans+'S'))
nx = int((x%1000)*10 + x/1000)
if nx<10000 and visited[nx] == 0:
visited[nx] = 1
q.append((nx, ans+'L'))
nx = int((x%10)*1000 + x/10)
if nx<10000 and visited[nx] == 0:
visited[nx] = 1
q.append((nx, ans+'R'))
n = int(input())
for _ in range(n):
s, e = map(int, sys.stdin.readline().split())
visited = [0]*10000
print(bfs(visited, s, e))