1
- import math
1
+ from collections import deque
2
2
3
- def double (n1 , n2 ):
4
- if n1 == 0 :
5
- return - 1
6
- if n1 < n2 :
7
- if n2 % (2 * n1 ) == 0 :
8
- log_n1 = math .log2 (n2 // (2 * n1 ))
9
- if log_n1 .is_integer ():
10
- return int (log_n1 ) + 1
11
- return - 1
12
- else :
13
- n1 = (2 * n1 ) % 10000
14
- if n1 == n2 :
15
- return 1
16
- return - 1
17
-
18
- def diff (n1 , n2 ):
19
- return min (abs (n1 - n2 ), 9999 - abs (n1 - n2 ) + 1 )
3
+ def dslr (start , target ):
4
+ visited = [False ] * 10000
5
+ queue = deque ([(start , "" )])
20
6
21
- def shift (n1 , n2 , direction ):
22
- a = str (n1 ).zfill (4 )
23
- b = str (n2 ).zfill (4 )
24
- count = 0
25
- for _ in range (len (a )):
26
- if int (a ) == int (b ):
27
- return count
28
- if direction == "L" :
29
- a = a [1 :] + a [0 ]
30
- else :
31
- a = a [- 1 ] + a [:- 1 ]
32
- count += 1
33
- return - 1
7
+ while queue :
8
+ current , commands = queue .popleft ()
9
+
10
+ if current == target :
11
+ return commands
12
+
13
+ D = (2 * current ) % 10000
14
+ if not visited [D ]:
15
+ visited [D ] = True
16
+ queue .append ((D , commands + "D" ))
17
+
18
+ S = 9999 if current == 0 else current - 1
19
+ if not visited [S ]:
20
+ visited [S ] = True
21
+ queue .append ((S , commands + "S" ))
22
+
23
+ L = (current % 1000 ) * 10 + current // 1000
24
+ if not visited [L ]:
25
+ visited [L ] = True
26
+ queue .append ((L , commands + "L" ))
27
+
28
+ R = (current % 10 ) * 1000 + current // 10
29
+ if not visited [R ]:
30
+ visited [R ] = True
31
+ queue .append ((R , commands + "R" ))
34
32
35
33
N = int (input ())
36
34
for _ in range (N ):
37
35
n1 , n2 = map (int , input ().split ())
38
- min_count = float ('inf' )
39
- flag = None
40
-
41
- count_double = double (n1 , n2 )
42
- if count_double != - 1 and count_double < min_count :
43
- min_count = count_double
44
- flag = "D"
45
-
46
- count_diff = diff (n1 , n2 )
47
- if count_diff < min_count :
48
- min_count = count_diff
49
- flag = "S"
50
-
51
- count_L = shift (n1 , n2 , "L" )
52
- if count_L != - 1 and count_L < min_count :
53
- min_count = count_L
54
- flag = "L"
55
-
56
- count_R = shift (n1 , n2 , "R" )
57
- if count_R != - 1 and count_R < min_count :
58
- min_count = count_R
59
- flag = "R"
60
-
61
- if flag == "D" :
62
- print ("D" * min_count )
63
- elif flag == "S" :
64
- print ("S" * min_count )
65
- elif flag == "L" :
66
- print ("L" * min_count )
67
- elif flag == "R" :
68
- print ("R" * min_count )
36
+ print (dslr (n1 , n2 ))
0 commit comments