/* Topcoder SRM 702 D1 300-pointer. GridSortMax James S. Plank Sun Nov 20 11:40:05 EST 2016 */ #include #include #include #include #include using namespace std; class GridSortMax { public: string findMax(int n, int m, vector grid); }; string GridSortMax::findMax(int n, int m, vector G) { int i, j; /* Temporary variables. */ int v; /* The value that we're focusing on (will go 1, 2, 3, etc.) */ int vr, vc; /* V's current row and column */ int tr, tc; /* The target row and column for V */ string rv; /* The return string */ vector VR, VC; /* These are vectors that hold vr and vc for each v. */ vector VR_Swapped; /* Where has each row been swapped to? (-1 if unswapped yet) */ vector VC_Swapped; /* Where has each column been swapped to? */ vector TR_Swapped; /* Which row was swapped here? (-1 if unsapped yet) */ vector TC_Swapped; /* Which column was swapped here? */ /* Calculate VR and VC from G. We're going to look at values of v from 1 to n*m, so we need VR and VC to have n*m+1 elements, and we'll ignore element 0. */ VR.resize(G.size()+1); VC.resize(G.size()+1); for (i = 0; i < G.size(); i++) { v = G[i]; VR[v] = i/m; VC[v] = i%m; } /* Now, run through the values of v from 1 to n*m, and do the steps that I outlined in the writeup. */ VR_Swapped.resize(n, -1); VC_Swapped.resize(m, -1); TR_Swapped.resize(n, -1); TC_Swapped.resize(m, -1); for (v = 1; v <= n*m; v++) { vr = VR[v]; vc = VC[v]; tr = (v-1)/m; tc = (v-1)%m; // printf("v = %d. vr:%d vc:%d tr:%d tc:%d\n", v, vr, vc, tr, tc); /* Each of these follows the bullets in the writeup in order: First case is when you can swap vr and vc to their correct place. */ if (VR_Swapped[vr] == -1 && VC_Swapped[vc] == -1 && TR_Swapped[tr] == -1 && TC_Swapped[tc] == -1) { VR_Swapped[vr] = tr; VC_Swapped[vc] = tc; TR_Swapped[tr] = vr; TC_Swapped[tc] = vc; rv.push_back('1'); /* Here, you haven't swapped VR, but the target row is occupied. (Same with the column) */ } else if (VR_Swapped[vr] == -1 && TR_Swapped[tr] != -1) { rv.push_back('0'); } else if (VC_Swapped[vc] == -1 && TC_Swapped[tc] != -1) { rv.push_back('0'); /* You have swapped vr, but not to the target row. (Same with teh column) */ } else if (VR_Swapped[vr] != -1 && TR_Swapped[tr] != vr) { rv.push_back('0'); } else if (VC_Swapped[vc] != -1 && TC_Swapped[tc] != tc) { rv.push_back('0'); /* You have swapped the row already to its proper place, and you can swap the column. */ } else if (VC_Swapped[vc] == -1 && TC_Swapped[tc] == -1) { VC_Swapped[vc] = tc; TC_Swapped[tc] = vc; rv.push_back('1'); /* You have swapped the column already to its proper place, and you can swap the row. */ } else if (VR_Swapped[vr] == -1 && TR_Swapped[tr] == -1) { VR_Swapped[vr] = tr; TR_Swapped[tr] = vr; rv.push_back('1'); /* The row and column are already swapped to their correct place. */ } else rv.push_back('1'); } return rv; }