HDU 1195(bfs)

我就是我 2022-09-20 11:25 295阅读 0赞

题意:如题。

  1. #include <iostream>
  2. #include <cstring>
  3. #include <string>
  4. #include <queue>
  5. using namespace std;
  6. bool visit[10000];
  7. const int temp[5] = {0, 1000, 100, 10, 1};
  8. /*
  9. int swap(int num, int x, int y)
  10. {
  11. int temp[5], i = 4;
  12. while (num)
  13. {
  14. temp[i--] = num % 10;
  15. num /= 10;
  16. }
  17. temp[x] ^= temp[y];
  18. temp[y] ^= temp[x];
  19. temp[x] ^= temp[y];
  20. num = 0, i = 1, x = 1000;
  21. while (i < 5)
  22. {
  23. num += temp[i++] * x;
  24. x /= 10;
  25. }
  26. return num;
  27. }
  28. */
  29. int swap(int num, int x, int y)
  30. {
  31. int a = num / temp[x] % 10;
  32. int b = num / temp[y] % 10;
  33. return num - a * temp[x] - b * temp[y] + a * temp[y] + b * temp[x];
  34. }
  35. int _add(int num, int x)
  36. {
  37. int a = num / temp[x] % 10;
  38. if (a == 9)
  39. a = -8 * temp[x];
  40. else a = temp[x];
  41. return num + a;
  42. }
  43. int _minus(int num, int x)
  44. {
  45. int a = num / temp[x] % 10;
  46. if (a == 1)
  47. a = 8 * temp[x];
  48. else a = -temp[x];
  49. return num + a;
  50. }
  51. int BFS(int start, int target)
  52. {
  53. memset(visit, false, sizeof (visit));
  54. visit[start] = true;
  55. queue<int> q;
  56. int p, n, i, j, pre = 1, sum = 0, step = 1;
  57. q.push(start);
  58. while (!q.empty())
  59. {
  60. p = q.front(), q.pop();
  61. for (i = 1; i <= 4; ++i)
  62. {
  63. for (j = 0; j < 3; ++j)
  64. {
  65. if (j == 0)
  66. {
  67. if (i == 4) continue;
  68. n = swap(p, i, i + 1);
  69. }
  70. else if (j == 1)
  71. n = _add(p, i);
  72. else n = _minus(p, i);
  73. if (n == target)
  74. return step;
  75. else if (!visit[n])
  76. {
  77. visit[n] = true;
  78. q.push(n);
  79. ++sum;
  80. }
  81. }
  82. }
  83. if (--pre == 0)
  84. {
  85. pre = sum;
  86. sum = 0;
  87. ++step;
  88. }
  89. }
  90. return -1;
  91. }
  92. int main()
  93. {
  94. int T;
  95. int start, target;
  96. cin >> T;
  97. while (T--)
  98. {
  99. cin >> start >> target;
  100. cout << BFS(start, target) << endl;
  101. }
  102. }

发表评论

表情:
评论列表 (有 0 条评论,295人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HDU 1312(BFS)

    题意:“.”是red方格,“\”是black方格,“@”是起点。求从起点开始走,可以到达的方格(包括起点),red方格不能走,相当于墙壁。   include <c

    相关 HDU 1242(bfs)

    题意:一个朋友拯救angel,'a' 是angel, 'x'是士兵, 'r'是朋友,'\'是墙壁。没走一步花费一个单位的时间,遇到士兵与士兵搏斗花费一个单位的时间,求最短时间。

    相关 HDU 1240(bfs)

    题意:给出一个三维空间,宇宙飞船的起始地点,目标地点,求最短飞行距离。   include <iostream> include <str

    相关 HDU 1728(BFS)

    问题描述: 给定一个m × n (m行, n列)的迷宫,迷宫中有两个位置,gloria想从迷宫的一个位置走到另外一个位置,当然迷宫中有些地方是空地,gloria可以穿越,有些