You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.1 KiB
2.1 KiB
完美方阵
小明很喜欢矩阵,在他的心目中这样的矩阵能够被称为“完美方阵”:这个方阵的 n
行与 n
列当中,每行的数字之和必须相同,每列的数字之和也必须相同。
现在你找来一些方阵,你想知道小明是否愿称之为完美方阵。
输入格式
第一行输入一个数 n
,表示一个方阵的行列数;
之后 n
行,每行 n
个数,表示方阵中的每个元素 ,以空格隔开;
输出格式
若这个方阵是完美方阵,输出“YES
”,否则输出“NO
”。
输入样例
3
3 4 8
7 2 6
5 9 1
输出样例
YES
原始AC版本
#include <iostream>
using namespace std;
const int N = 110;
int a[N][N];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> a[i][j];
//首行累加和
int s = 0;
for (int i = 1; i <= n; i++) s += a[1][i];
//所有行进行判断
for (int i = 1; i <= n; i++) {
int t = 0;
for (int j = 1; j <= n; j++) t += a[i][j];
if (t != s) {
puts("NO");
return 0;
}
}
// 所有列进行判断
for (int j = 1; j <= n; j++) {
int t = 0;
for (int i = 1; i <= n; i++) t += a[i][j];
if (t != s) {
puts("NO");
return 0;
}
}
puts("YES");
return 0;
}
优化后版本
#include <iostream>
using namespace std;
const int N = 110;
int a[N], b[N];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
int x;
cin >> x;
a[j] += x;
b[i] += x;
}
for (int i = 1; i <= n; i++)
if (a[i] != a[1] || b[i] != a[1]) {
puts("NO");
return 0;
}
puts("YES");
return 0;
}