1. 程式人生 > >ZOJ.2835 Magic Square【水】 2015/09/23

ZOJ.2835 Magic Square【水】 2015/09/23

Magic Square
Time Limit: 2 Seconds      Memory Limit: 65536 KB
In recreational mathematics, a magic square of n-degree is an arrangement of n2 numbers, distinct integers, in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant. For example, the picture below shows a 3-degree magic square using the integers of 1 to 9.

Given a finished number square, we need you to judge whether it is a magic square.


Input

The input contains multiple test cases.

The first line of each case stands an only integer N (0 < N < 10), indicating the degree of the number square and then N lines follows, with N positive integers in each line to describe the number square. All the numbers in the input do not exceed 1000.

A case with N = 0 denotes the end of input, which should not be processed.


Output

For each test case, print "Yes" if it's a magic square in a single line, otherwise print "No".


Sample Input

2
1 2
3 4
2
4 4
4 4
3
8 1 6
3 5 7
4 9 2
4
16 9 6 3
5 4 15 10
11 14 1 8
2 7 12 13
0

Sample Output

No
No
Yes
Yes
Author: JIANG, Hao
Source: Zhejiang University Local Contest 2007
判斷每一行,每一列,對角線上的數字之和是否相等,但是n^2個數全都不相同
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>

using namespace std;

int main(){
    int n,p[12][12],i,j,num[1010];
    while( ~scanf("%d",&n),n ){
        memset(num,0,sizeof(num));
        bool flag = false;
        for( i = 0 ; i < n ; ++i ){
            for( j = 0 ; j < n ; ++j ){
                scanf("%d",&p[i][j]);
                num[p[i][j]]++;
                if( num[p[i][j]] >= 2 ){
                    flag = true;
                }
            }
        }
        if( flag ){
            printf("No\n");
            continue;
        }
        int ret = 0,ans1,ans2;
        for( i = 0 ; i < n ; ++i )
            ret += p[i][i];
        for( i = 0 ; i < n ; ++i ){
            ans1 = ans2 = 0;
            for( j = 0 ; j < n ; ++j ){
                ans1 += p[i][j];
                ans2 += p[j][i];
            }
            if( ans1 != ret ){
                flag = true;
                break;
            }
            if( ans2 != ret ){
                flag = true;
                break;
            }
        }
        ans1 = 0;
        for( i = 0 ; i < n ; ++i )
            ans1 += p[n-i-1][i];
        if( ans1 != ret )
            flag = true;
        if( flag )
            printf("No\n");
        else printf("Yes\n");
    }
    return 0;
}