• Source
    1. #include <iostream>
    2. #include <cstdio>
    3. #include <vector>
    4. #include <queue>
    5. #include <utility>
    6. using namespace std;
    7.  
    8. typedef vector<int> vi;
    9. typedef long long ll;
    10. typedef pair<int,int> pii;
    11. typedef vector<pii> vii;
    12.  
    13. #define pb push_back
    14. #define fst first
    15. #define snd second
    16. #define ri(x) scanf("%d", &x)
    17. #define rii(x,y) scanf("%d%d", &x, &y)
    18. #define FOR(i,S,E) for(int i=S; i<E; i++)
    19.  
    20. struct Node {
    21. int val, cursor, steps;
    22. };
    23.  
    24. void Swap(int &b, int cursor, int z) {
    25. int aux = b, idx=1;
    26. for(int i=5; i != cursor; i--) {
    27. aux /= 10;
    28. idx *= 10;
    29. }
    30. int x = aux % 10, y = (b/int(z))%10;
    31. b += - y*int(z) + x*int(z);
    32. b += - x*int(idx) + y*int(idx);
    33. }
    34.  
    35. void Ch(int &b, int cursor, int op) {
    36. int idx=1, aux=b;
    37. for(int i=5; i != cursor; i--) {
    38. idx *= 10;
    39. aux /= 10;
    40. }
    41. int x = aux%10;
    42. if (op && x == 9) return;
    43. if (!op && x == 0) return;
    44. //Up
    45. if (op) b += idx;
    46. else b -= idx;
    47. }
    48.  
    49. int main () {
    50. int T; ri(T);
    51. vector<vi> vis; vis.resize(int(1e6));
    52. FOR(i,0,int(1e6)) {
    53. vis[i].resize(6, -1);
    54. }
    55. while(T--) {
    56. int init, passw;
    57. rii(init, passw);
    58. queue<Node> q;
    59. q.push({init, 0, 0});
    60. int ans=0;
    61.  
    62. while(!q.empty()) {
    63. Node p = q.front();
    64. q.pop();
    65.  
    66. if (p.val == passw) {
    67. ans = p.steps;
    68. break;
    69. }
    70. vis[p.val][p.cursor] = T;
    71.  
    72. //Swap0
    73. int aux = p.val;
    74. Swap(aux, p.cursor, int(1e5));
    75. //printf("\t\t%d %d\n", aux, p.cursor);
    76. if (vis[aux][p.cursor] != T) q.push({aux, p.cursor, p.steps+1});
    77.  
    78. //Swap1
    79. aux = p.val;
    80. Swap(aux, p.cursor, 1);
    81. if (vis[aux][p.cursor] != T) q.push({aux, p.cursor, p.steps+1});
    82.  
    83. //Up
    84. aux = p.val;
    85. Ch(aux, p.cursor, 1);
    86. if (vis[aux][p.cursor] != T) q.push({aux, p.cursor, p.steps+1});
    87.  
    88. //DOwn
    89. aux = p.val;
    90. Ch(aux, p.cursor, 0);
    91. if (vis[aux][p.cursor] != T) q.push({aux, p.cursor, p.steps+1});
    92.  
    93. //Left
    94. if (p.cursor > 0 && vis[p.val][p.cursor-1] != T)
    95. q.push({p.val, p.cursor-1,p.steps+1});
    96.  
    97. //Right
    98. if (p.cursor < 5 && vis[p.val][p.cursor+1] != T)
    99. q.push({p.val, p.cursor+1, p.steps+1});
    100. }
    101. printf("%d\n", ans);
    102. }
    103. }
    104.