Hi,
I spent almost an hour figuring out what the error in my code was. It works for many small test cases and stress testing on large values also ran properly. I have commented the code for better readability. Please help!
Also, what are the things to look for other than invalid references when we get this error?
#include <bits/stdc++.h> using namespace std ; int A[100002]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while(t--){ memset(A, 0, sizeof(A)); int n, m, el; cin >> n >> m; int mtx[n][m]; for (int i = 0; i < n * m; i++){ // filling counts cin >> el; A[el]++; } if (m % 2 == 0){ // even cols int flag = 1; for (int i = 0; i < 100001; i++){ if (A[i] % 2 == 1){ // didn't find flag = 0; break; } } if (flag) { // found int i1=0,i2=m-1,j=0; for (int i = 0; i < 100001; i++){ // filling matrix while (A[i] > 0){ mtx[j][i1] = i; mtx[j][i2] = i; i1++; i2--; A[i]-=2; if (i1 - 1 == i2) { // crossing over i1 = 0; i2 = m - 1; j++; } } } for(int a = 0; a < n; a++){ // print for (int b = 0; b < m; b++){ cout << mtx[a][b] << " "; } cout << endl ; } } else { cout << "-1\n"; } } else { int cnt = 0; for (int i = 0; i < 100001; i++){ // checking counts if(A[i] % 2 == 1){ cnt ++; } } if (cnt > n){ // shouldn't be more than n cout << "-1\n"; } else { int i1=0,i2=m-1,j=0; // j is row index, i1 and i2 are col indexes for (int i = 0; i < 100001; i++){ // fill rows except center while (A[i] > 0){ if (j == n) // filled break ; if (i1 == i2) { // fill center later i1 = 0; i2 = m - 1; j++; } else { mtx[j][i1] = i; mtx[j][i2] = i; i1++; i2--; A[i]-=2; } } } i1 = m/2, j = 0; // filling center now for (int i = 0; i < 100001; i++){ while (A[i] > 0){ mtx[j][i1] = i; A[i]--; j++; } } for(int a = 0; a < n; a++){ // print matrix for (int b = 0; b < m; b++){ cout << mtx[a][b] << " "; } cout << endl ; } } } } }