首页 > 代码库 > Gym - 100735E Restore

Gym - 100735E Restore

E - Restore

题意:输入一个n,输入一个对角线空缺(为0)的n*n的矩阵,要求每一行每一列和对角线的和相同,输出完整的矩阵。

解法:设每一行的和都是sum,用一个h[]数组存每一行的和。则可得a[0][0] = sum-h[0], a[1][1] = sum-h[1], a[2][2] = sum-h[2]......同时所有对角线的和也为sum,则可得公式 sum-h[0]+sum-h[1]+...+sum-h[n-1] = sum, 设所有h[x]的和为summ, 即n*sum-summ=sum, 即可得sum = summ/(n-1),后面由式子a[i][i] = sum-h[i]便可求得。

注意:a[i][j]的取值范围!?-?1012?≤?Aij?≤?1012, 要用long long去存。

 

typedef long long ll;
ll a[105][105]; ll h[105]; void solve() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%lld", &a[i][j]); h[i] += a[i][j]; } } ll summ=0; for (int i = 0; i < n; i++) { summ+=h[i]; } ll sum = summ/(n-1); for (int i = 0; i < n; i++) { a[i][i] = sum-h[i]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j) printf(" "); printf("%lld", a[i][j]); } printf("\n"); } } int main() { int t = 1; //scanf("%d", &t); while(t--) solve(); return 0; }

 

Gym - 100735E Restore