a53

yinyang

a53
Mar 14th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<algorithm>
  3. #include<cassert>
  4. using namespace std;
  5.  
  6. #define NMAX 104
  7.  
  8. int n, m, matrix[NMAX][NMAX], newMatrix[NMAX][NMAX];
  9. int lineIndex[NMAX], columIndex[NMAX];
  10.  
  11. void readInput() {
  12. scanf("%d%d",&n,&m);
  13. assert(1 <= n && n <= 100 && 1 <= m && m <= 100);
  14. for(int i = 1; i <= n; i++)
  15. for(int j = 1; j <= m; j++) {
  16. scanf("%d",&matrix[i][j]);
  17. assert(1 <= matrix[i][j] && matrix[i][j] <= n * m);
  18. }
  19. }
  20.  
  21. int cmpLine(const int& a, const int& b) {
  22. for(int i = 1; i <= m; i++)
  23. if(matrix[a][i] != matrix[b][i])
  24. return matrix[a][i] < matrix[b][i];
  25. return a < b;
  26. }
  27.  
  28. int cmpColum(const int& a, const int& b) {
  29. for(int i = 1; i <= n; i++)
  30. if(matrix[i][a] != matrix[i][b])
  31. return matrix[i][a] < matrix[i][b];
  32. return a < b;
  33. }
  34.  
  35. void sortMatrix() {
  36. for(int i = 1; i <= n; i++) {
  37. lineIndex[i] = i;
  38. }
  39. sort(lineIndex + 1, lineIndex + n + 1, cmpLine);
  40.  
  41. for(int i = 1; i <= m; i++) {
  42. columIndex[i] = i;
  43. }
  44. sort(columIndex + 1, columIndex + m + 1, cmpColum);
  45.  
  46. for(int i = 1; i <= n; i++)
  47. for(int j = 1; j <= m; j++) {
  48. newMatrix[i][j] = matrix[lineIndex[i]][columIndex[j]];
  49. }
  50. }
  51.  
  52. bool checkSolution() {
  53. for(int i = 1; i <= n; i++) {
  54. for(int j = 1; j <= m; j++) {
  55. if(newMatrix[i][j] < newMatrix[i - 1][j] || newMatrix[i][j] < newMatrix[i][j - 1])
  56. return false;
  57. }
  58. }
  59. return true;
  60. }
  61.  
  62. void writeOutput() {
  63. if(!checkSolution()) {
  64. printf("-1\n");
  65. return ;
  66. }
  67. int answer = 0;
  68.  
  69. for(int i = 2; i <= n; i++)
  70. for(int j = 1; j < i; j++)
  71. answer += (lineIndex[i] < lineIndex[j]);
  72.  
  73. for(int i = 2; i <= m; i++)
  74. for(int j = 1; j < i; j++)
  75. answer += (columIndex[i] < columIndex[j]);
  76.  
  77. printf("%d\n", answer);
  78. }
  79.  
  80. int main () {
  81.  
  82. freopen("yinyang.in","r",stdin);
  83. freopen("yinyang.out","w",stdout);
  84.  
  85. readInput();
  86. sortMatrix();
  87. writeOutput();
  88.  
  89. return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment