题目链接:http://codeforces.com/contest/711/problem/B
题意:n*n的矩阵空了一个,填一个数让它变成幻方,不能的话输出-1。
记录每行每列的和,任取两个不包括空的行或者列看看是否相等,如果不相等则可以退出。否则根据其中一个数推出空格的数,更新行列后并算出对角线的值判断。注意最后数据范围是a~1e18,不知道是不是因为这个判断好多人fst。
1 #include <algorithm> 2 #include <iostream> 3 #include <iomanip> 4 #include <cstring> 5 #include <climits> 6 #include <complex> 7 #include <fstream> 8 #include <cassert> 9 #include <cstdio> 10 #include <bitset> 11 #include <vector> 12 #include <deque> 13 #include <queue> 14 #include <stack> 15 #include <ctime> 16 #include <set> 17 #include <map> 18 #include <cmath> 19 using namespace std; 20 #define fr first 21 #define sc second 22 #define cl clear 23 #define BUG puts("here!!!") 24 #define W(a) while(a--) 25 #define pb(a) push_back(a) 26 #define Rint(a) scanf("%d", &a) 27 #define Rll(a) scanf("%I64d", &a) 28 #define Rs(a) scanf("%s", a) 29 #define Cin(a) cin >> a 30 #define FRead() freopen("in", "r", stdin) 31 #define FWrite() freopen("out", "w", stdout) 32 #define Rep(i, len) for(int i = 0; i < (len); i++) 33 #define For(i, a, len) for(int i = (a); i < (len); i++) 34 #define Cls(a) memset((a), 0, sizeof(a)) 35 #define Clr(a, x) memset((a), (x), sizeof(a)) 36 #define Full(a) memset((a), 0x7f7f7f, sizeof(a)) 37 #define lrt rt << 1 38 #define rrt rt << 1 | 1 39 #define pi 3.14159265359 40 #define RT return 41 #define lowbit(x) x & (-x) 42 #define onecnt(x) __builtin_popcount(x) 43 typedef long long LL; 44 typedef long double LD; 45 typedef unsigned long long ULL; 46 typedef pair<int, int> pii; 47 typedef pair<string, int> psi; 48 typedef pair<LL, LL> pll; 49 typedef map<string, int> msi; 50 typedef vector<int> vi; 51 typedef vector<LL> vl; 52 typedef vector<vl> vvl; 53 typedef vector<bool> vb; 54 55 const int maxn = 550; 56 int n; 57 LL G[maxn][maxn]; 58 int px, py; 59 LL sx[maxn], sy[maxn]; 60 LL pp, qq; 61 int main() { 62 // FRead(); 63 while(~Rint(n)) { 64 Cls(sx); Cls(sy); pp = qq = 0; 65 For(i, 1, n+1) { 66 For(j, 1, n+1) { 67 cin >> G[i][j]; 68 if(G[i][j] == 0) { 69 px = i; 70 py = j; 71 } 72 sx[i] += G[i][j]; 73 sy[j] += G[i][j]; 74 } 75 } 76 if(n == 1) { 77 puts("1"); 78 continue; 79 } 80 bool flag = 0; 81 LL tmp = -1; 82 For(i, 1, n+1) { 83 if(i == px || i == py) continue; 84 if(sx[i] != sy[i]) flag = 1; 85 else tmp = sx[i]; 86 } 87 if(flag) { 88 puts("-1"); 89 continue; 90 } 91 G[px][py] = tmp - sx[px]; 92 sx[px] += G[px][py]; sy[py] += G[px][py]; 93 For(i, 1, n+1) { 94 pp += G[i][i]; 95 qq += G[i][n-i+1]; 96 } 97 For(i, 1, n+1) { 98 if(sx[i] != sy[i]) flag = 1; 99 } 100 For(i, 1, n) { 101 if(sx[i] != sx[i+1]) flag = 1; 102 if(sy[i] != sy[i+1]) flag = 1; 103 } 104 if(!(pp == qq && pp == sx[1])) flag = 1; 105 if(flag) { 106 puts("-1"); 107 continue; 108 } 109 if(G[px][py] >= 1 && G[px][py] <= 1e18) { 110 cout << G[px][py] << endl; 111 } 112 else puts("-1"); 113 114 } 115 RT 0; 116 }