voidsetMAndN(int N){ int min = 100001; // i is n for (int i = 1; i <= sqrt(N); i++) { if (N % i == 0) { // j is m int j = N / i; // m - n is the most small. if (min > j - i) { m = j; n = i; min = m - n; } } } }
voidsetMatrix(){ matrix = newint *[m]; for (int i = 0; i < m; i++) { matrix[i] = newint[n]; } }
voidfillMatrix(int N){ int index = N - 1; int i = 0, j = 0; while (index >= 0) { // right. for (; index >= 0 && j < n && matrix[i][j] == 0; j++) { matrix[i][j] = a[index--]; } i++; j--; // down. for (; index >= 0 && i < m && matrix[i][j] == 0; i++) { matrix[i][j] = a[index--]; } i--; j--;