fork download
  1. #include <vector>
  2. #include <string>
  3. #include <algorithm>
  4. #include <iostream>
  5. #include <iomanip>
  6.  
  7. using namespace std;
  8.  
  9. const int N = 5;
  10.  
  11. int b[N][N];
  12. int er = N-1, ec = N-1;
  13.  
  14. int coord(int r, int c) { return r*N+c; }
  15.  
  16. void move()
  17. {
  18. int olr = er, olc = ec;
  19. for(bool ok = false;!ok;)
  20. {
  21. switch(rand()%4)
  22. {
  23. case 0: if (er > 0) { er--; ok = true; } break;
  24. case 1: if (ec < N-1) { ec++; ok = true; } break;
  25. case 2: if (er < N-1) { er++; ok = true; } break;
  26. case 3: if (ec > 0) { ec--; ok = true; } break;
  27. }
  28. }
  29. cout << er << " <> " << ec << endl;
  30. int t = b[olr][olc];
  31. b[olr][olc] = b[er][ec];
  32. b[er][ec] = t;
  33. }
  34.  
  35. bool invariant()
  36. {
  37. const int M = N*N - 1;
  38. int a[M];
  39. for(int k = 0, i = 0; i < N; ++i)
  40. for(int j = 0; j < N; ++j)
  41. if (b[i][j]) a[k++] = b[i][j];
  42.  
  43. for(int i = 0; i < M; ++i) cout << a[i] << " "; cout << endl;
  44.  
  45. int sum = 0;
  46. for(int i = 0; i < M - 1; ++i)
  47. for(int j = i+1; j < M; ++j)
  48. if (a[i] > a[j]) sum++;
  49.  
  50. sum += er+1;
  51.  
  52. cout << sum << endl;
  53. return sum%2 == N%2;
  54. }
  55.  
  56.  
  57.  
  58.  
  59. int main(int argc, char * argv[])
  60. {
  61. for(int k = 0, i = 0; i < N; ++i)
  62. for(int j = 0; j < N; ++j)
  63. b[i][j] = ++k;
  64. b[N-1][N-1] = 0;
  65.  
  66. for(;;)
  67. {
  68. move();
  69. if (!invariant())
  70. {
  71. cout << "Error!!!!!\n";
  72. break;
  73. }
  74. }
  75. }
  76.  
Success #stdin #stdout 0s 5664KB
stdin
Standard input is empty
stdout
4 <> 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
5
4 <> 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
5
4 <> 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
5
4 <> 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
5
4 <> 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
5
3 <> 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 21 22 23 19 24 
8
Error!!!!!