fork download
  1. #include <iostream>
  2. using namespace std;
  3. #define ll long long
  4.  
  5. int main()
  6. {
  7. int n;
  8. cin >> n;
  9. ll arr[n][n];
  10. int i, j;
  11. int row = 10000, col = 10000;
  12. for(i = 0; i < n; i++) {
  13. for(j = 0; j < n; j++) {
  14. cin >> arr[i][j];
  15. if(arr[i][j] == 0) {
  16. row = i;
  17. col = j;
  18. }
  19. }
  20. }
  21. ll sumR = 0, sumR2 = 0;
  22. ll sumC = 0, sumC2 = 0;
  23. ll sumD = 0, sumD2 = 0;
  24. int flag = 0;
  25. int exec = 0;
  26. for(i = 0; i < n; i++) {
  27. if(i != row) {
  28.  
  29. for(j = 0; j < n; j++)
  30. sumR += arr[i][j];
  31. if(exec != 0) {
  32. if(sumR != sumR2) {
  33. flag = 1;
  34. break;
  35. }
  36. }
  37.  
  38. sumR2 = sumR;
  39. sumR = 0;
  40.  
  41. exec++;
  42. }
  43. }
  44. //cout << row << " " << col << endl;
  45. exec = 0;
  46. for(j = 0; j < n; j++) {
  47. if(j != col) {
  48. //cout << i << " " << j << endl;
  49. for(i = 0; i < n; i++)
  50. sumC += arr[i][j];
  51. //cout << sumC << " " << sumC2 << endl;
  52. if(exec != 0) {
  53. if(sumC != sumC2) {
  54. flag = 1;
  55. break;
  56. }
  57. }
  58. sumC2 = sumC;
  59. sumC = 0;
  60.  
  61. exec++;
  62. //cout << sumC << " " << sumC2 << endl;
  63. }
  64. }
  65. int flag2 = 0;
  66. for(i = 0, j = 0; i < n && j < n; i++, j++) {
  67. if(i == row && j == col) {
  68. sumD = 0;
  69. flag2 = 1;
  70. break;
  71. } else {
  72. sumD += arr[i][j];
  73. }
  74. //cout << sumD << " ";
  75. }
  76. for(i = 0, j = n-1; i < n && j >= 0; i++, j--) {
  77. if(i == row && j == col) {
  78. sumD2 = 0;
  79. flag2 = 2;
  80. break;
  81. } else {
  82. sumD2 += arr[i][j];
  83. }
  84. //cout << endl << sumD2 << " ";
  85. }
  86. //cout << endl;
  87. ll ans = 0;
  88. ll s = 0;
  89. if(flag2 == 0) {
  90. if(sumR2 == sumC2 && sumR2 == sumD && sumR2 == sumD2) {
  91. //ll s = 0;
  92. for(j = 0; j < n; j++)
  93. s += arr[row][j];
  94. ans = sumR2 - s;
  95.  
  96.  
  97. }
  98. //cout << ans << " " << s << endl;
  99. } else if(flag2 == 1) {
  100. if(sumR2 == sumC2 && sumR2 == sumD2) {
  101. //ll s = 0;
  102. for(j = 0; j < n; j++)
  103. s += arr[row][j];
  104. ans = sumR2 - s;
  105. }
  106. //cout << ans << " " << s << endl;
  107. } else if(flag2 == 2) {
  108. if(sumR2 == sumC2 && sumR2 == sumD) {
  109. //ll s = 0;
  110. for(j = 0; j < n; j++)
  111. s += arr[row][j];
  112. ans = sumR2 - s;
  113.  
  114.  
  115. }
  116. //cout << ans << " " << s << endl;
  117. }
  118. //cout << sumR2 << " " << sumC2 << " " << sumD << " " << sumD2 << " " << flag << " " << flag2 << " " << ans << " " << s << endl;
  119. if(flag == 0 && ans > 0) {
  120. cout << ans << endl;
  121. } else
  122. cout << "-1" << endl;
  123. //cout << flag << ans;
  124. return 0;
  125. }
Runtime error #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty