#include <vector>
#include <iostream>
#include <iomanip>
#include <map>
#include <cmath>
#include <assert.h>

using namespace std;

vector<vector<int>> make(int m, map<int,int> els)
{
    vector<vector<int>> s(m,vector<int>(m,0));
    vector<vector<int>> f = s;
    // Расставляем дубли
    int col = 0;
    for(auto& x: els)
    {
        if (x.second > 1)
        {
            for(int j = 0; j < x.second; ++j)
            {
                s[(col+j)%m][j] = x.first;
                f[(col+j)%m][j] = 1;
            }
            col++;
            x.second = 0;
        }
    }
    // Расставляем остальные
    auto it = els.begin();
    if (it != els.end())
        for(int i = 0; i < m; ++i)
            for(int j = 0; j < m; ++j)
                if (f[i][j] == 0)
                {
                    while (it->second == 0) it++;
                    s[i][j] = it->first;
                    it++;
                }
    return s;
}


int main(int argc, const char * argv[])
{
    srand(time(0));

    int n = 25;

    int m = sqrt(n)+0.5;
    if (m*m != n) { cout << n  << " - не квадрат!\n"; return 0; }

    map<int,int> els;
    for(int k, i = 0; i < n; ++i)
    {
        k = rand()%40;
        els[k]++;
        cout << k << " ";
    }
    cout << endl << endl;

    int dbls = 0, max_dbl = 0;
    for(auto x: els)
    {
        if (x.second > 1) dbls++;
        if (x.second > max_dbl) max_dbl = x.second;
    }
    if (dbls > m || max_dbl > m) { cout << "Решения нет!\n"; return 0; }

    auto v = make(m,els);

    for(auto r: v)
    {
        for(auto c: r) cout << setw(2) << c << " ";
        cout << endl;
    }

}
