ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 9019 |
문제명 | DSLR |
레벨 | 골드 5 |
분류 |
BFS |
시간복잡도 | O(T*|E|) |
인풋사이즈 | T<=?, |E|=40000 |
사용한 언어 | Python |
제출기록 | 33964KB / 13704ms |
최고기록 | 3004ms |
해결날짜 | 2021/08/22 |
"""Solution code for "BOJ 9019. DSLR".
- Problem link: https://www.acmicpc.net/problem/9019
- Solution link: http://www.teferi.net/ps/problems/boj/9019
Tags: [BFS]
"""
import collections
import sys
def bfs(source, sink):
deq = collections.deque([source])
prev_state_and_cmd = [None] * 10000
while True:
n = deq.popleft()
next_states = [('D', n * 2 % 10000),
('S', n - 1 if n > 0 else 9999),
('L', n % 1000 * 10 + n // 1000),
('R', n % 10 * 1000 + n // 10)]
for cmd, v in next_states:
if prev_state_and_cmd[v] is None:
prev_state_and_cmd[v] = (n, cmd)
if v == sink:
return prev_state_and_cmd
deq.append(v)
def main():
T = int(sys.stdin.readline())
for _ in range(T):
A, B = [int(x) for x in sys.stdin.readline().split()]
prev_state_and_cmd = bfs(A, B)
cur = B
cmds = []
while cur != A:
cur, cmd = prev_state_and_cmd[cur]
cmds.append(cmd)
print(''.join(reversed(cmds)))
if __name__ == '__main__':
main()
"""Solution code for "BOJ 9019. DSLR".
- Problem link: https://www.acmicpc.net/problem/9019
- Solution link: http://www.teferi.net/ps/problems/boj/9019
Tags: [BFS]
"""
import collections
import sys
def bfs(source, sink, next_states):
deq = collections.deque([source])
prev = [None] * 10000
while True:
n = deq.popleft()
d, s, l, r = next_states[n]
if prev[d] is None:
prev[d] = n
deq.append(d)
if prev[s] is None:
prev[s] = n
deq.append(s)
if prev[l] is None:
prev[l] = n
deq.append(l)
if prev[r] is None:
prev[r] = n
deq.append(r)
if prev[sink] is not None:
return prev
def main():
next_states = [[n * 2 % 10000,
(n - 1) % 10000,
n % 1000 * 10 + n // 1000,
n % 10 * 1000 + n // 10] for n in range(10000)]
T = int(sys.stdin.readline())
for _ in range(T):
A, B = [int(x) for x in sys.stdin.readline().split()]
prev_states = bfs(A, B, next_states)
cur = B
cmds = []
while cur != A:
prev = prev_states[cur]
cmd = next_states[prev].index(cur)
cmds.append('DSLR'[cmd])
cur = prev
print(''.join(reversed(cmds)))
if __name__ == '__main__':
main()