Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<algorithm>
- #include<cassert>
- using namespace std;
- #define NMAX 104
- int n, m, matrix[NMAX][NMAX], newMatrix[NMAX][NMAX];
- int lineIndex[NMAX], columIndex[NMAX];
- void readInput() {
- scanf("%d%d",&n,&m);
- assert(1 <= n && n <= 100 && 1 <= m && m <= 100);
- for(int i = 1; i <= n; i++)
- for(int j = 1; j <= m; j++) {
- scanf("%d",&matrix[i][j]);
- assert(1 <= matrix[i][j] && matrix[i][j] <= n * m);
- }
- }
- int cmpLine(const int& a, const int& b) {
- for(int i = 1; i <= m; i++)
- if(matrix[a][i] != matrix[b][i])
- return matrix[a][i] < matrix[b][i];
- return a < b;
- }
- int cmpColum(const int& a, const int& b) {
- for(int i = 1; i <= n; i++)
- if(matrix[i][a] != matrix[i][b])
- return matrix[i][a] < matrix[i][b];
- return a < b;
- }
- void sortMatrix() {
- for(int i = 1; i <= n; i++) {
- lineIndex[i] = i;
- }
- sort(lineIndex + 1, lineIndex + n + 1, cmpLine);
- for(int i = 1; i <= m; i++) {
- columIndex[i] = i;
- }
- sort(columIndex + 1, columIndex + m + 1, cmpColum);
- for(int i = 1; i <= n; i++)
- for(int j = 1; j <= m; j++) {
- newMatrix[i][j] = matrix[lineIndex[i]][columIndex[j]];
- }
- }
- bool checkSolution() {
- for(int i = 1; i <= n; i++) {
- for(int j = 1; j <= m; j++) {
- if(newMatrix[i][j] < newMatrix[i - 1][j] || newMatrix[i][j] < newMatrix[i][j - 1])
- return false;
- }
- }
- return true;
- }
- void writeOutput() {
- if(!checkSolution()) {
- printf("-1\n");
- return ;
- }
- int answer = 0;
- for(int i = 2; i <= n; i++)
- for(int j = 1; j < i; j++)
- answer += (lineIndex[i] < lineIndex[j]);
- for(int i = 2; i <= m; i++)
- for(int j = 1; j < i; j++)
- answer += (columIndex[i] < columIndex[j]);
- printf("%d\n", answer);
- }
- int main () {
- freopen("yinyang.in","r",stdin);
- freopen("yinyang.out","w",stdout);
- readInput();
- sortMatrix();
- writeOutput();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment