fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <map>
  5. #include <cmath>
  6. #include <assert.h>
  7.  
  8. using namespace std;
  9.  
  10. vector<vector<int>> make(int m, map<int,int> els)
  11. {
  12. vector<vector<int>> s(m,vector<int>(m,0));
  13. vector<vector<int>> f = s;
  14. // Расставляем дубли
  15. int col = 0;
  16. for(auto& x: els)
  17. {
  18. if (x.second > 1)
  19. {
  20. for(int j = 0; j < x.second; ++j)
  21. {
  22. s[(col+j)%m][j] = x.first;
  23. f[(col+j)%m][j] = 1;
  24. }
  25. col++;
  26. x.second = 0;
  27. }
  28. }
  29. // Расставляем остальные
  30. auto it = els.begin();
  31. if (it != els.end())
  32. for(int i = 0; i < m; ++i)
  33. for(int j = 0; j < m; ++j)
  34. if (f[i][j] == 0)
  35. {
  36. while (it->second == 0) it++;
  37. s[i][j] = it->first;
  38. it++;
  39. }
  40. return s;
  41. }
  42.  
  43.  
  44. int main(int argc, const char * argv[])
  45. {
  46. srand(time(0));
  47.  
  48. int n = 25;
  49.  
  50. int m = sqrt(n)+0.5;
  51. if (m*m != n) { cout << n << " - не квадрат!\n"; return 0; }
  52.  
  53. map<int,int> els;
  54. for(int k, i = 0; i < n; ++i)
  55. {
  56. k = rand()%40;
  57. els[k]++;
  58. cout << k << " ";
  59. }
  60. cout << endl << endl;
  61.  
  62. int dbls = 0, max_dbl = 0;
  63. for(auto x: els)
  64. {
  65. if (x.second > 1) dbls++;
  66. if (x.second > max_dbl) max_dbl = x.second;
  67. }
  68. if (dbls > m || max_dbl > m) { cout << "Решения нет!\n"; return 0; }
  69.  
  70. auto v = make(m,els);
  71.  
  72. for(auto r: v)
  73. {
  74. for(auto c: r) cout << setw(2) << c << " ";
  75. cout << endl;
  76. }
  77.  
  78. }
  79.  
Success #stdin #stdout 0s 4284KB
stdin
Standard input is empty
stdout
24 36 5 30 25 17 29 39 11 5 27 18 26 8 22 26 0 21 11 29 26 12 5 36 20 

 5 36  0  8 12 
11  5 17 18 20 
26 11  5 21 22 
29 26 24 25 27 
36 29 26 30 39