sicily 1318 magic square 解题总结

summary

:

闲得慌,便逃课出来,突然有刷题的冲动,于是开始了刷水题之旅。很快一道水题就A了, 然后碰到了1318这道。

题目大意:

输入整数N,(n >= 3 && n <= 15),构造魔方阵,使每行,每列及对角线的数字的和都相等,
然后输出这个和,并且输出这个矩阵。

分析:

根据提示:Imagine that the square is rounded. That is, the last row is connected with the first row and the last column is connected with the first column. As shown in the examples, the starting point is the center of the first row and observe how the numbers are placed following diagonals. There is only one more thing to observe, what happens when you find a cell that is already in use.

明显,人家已经告诉我们算法是怎样的了,以前看射雕英雄传,黄蓉可是很快就算出来了, 当时看着很神奇,现在觉得是小菜一碟,看来学计算机的还是最聪明的。 把矩阵想像成一个首尾连接的球,第一个数必在第一行的中间,下一个数为它的下n-1行和下一列, 持续下去,即可解决!

但是,一般人解决这种水题是没问题的,关键是,你会做,但是你A不了。看看题目的要求, 每个测试数据之间要有一空行,并且,不是矩阵数据之间有一空格,而是每个数字前面是一空格 (这个错误害得我WA了N次,太坑爹了。。。)

代码:

#include <stdio.h>

int main()
{
    int n,i,j,k,a[20][20],sum;
    int flag = 0;
    while(scanf("%d", &n) != EOF){
        flag++;
        if(flag > 1){
            printf("\n");
        }
        sum = (n + 1) * n * (n - 1) / 2 + n;
        printf("n=%d, sum=%d\n",n,sum);
        for(i = 0; i < n; i++){
            for(j = 0; j < n; j++){
                a[i][j] = 0;
            }
        }
        i = 0;
        j = n / 2;
        a[i][j] = 1;
        for(k = 2; k <= n * n; k++){
            int fi = 0,fj = 0;
            i += n - 1;
            if(i >= n){
                i = i - n;
                fi = 1;
            }
            j++;
            if(j >= n){
                j = j - n;
                fj = 1;
            }
            if(a[i][j] == 0){
                a[i][j] = k;
            }else{
                if(fi){
                    i += n;
                }
                i = i - (n - 1) + 1;
                if(i >= n){
                    i = i - n;
                }
                if(fj){
                    j += n;
                }
                j--;
                if(j < 0){
                    j = n + j;
                }
                a[i][j] = k;
            }
        }
        for(i = 0; i < n; i++){
            /*if(n * n >= 100)
                printf("%3d",a[i][0]);
            else if(n * n >= 10)
                printf("%2d",a[i][0]);
            else
                printf("%d",a[i][0]);*/
            for(j = 0; j < n; j++){
                if(n * n >= 100)
                    printf(" %3d",a[i][j]);
                else if(n * n >= 10)
                    printf(" %2d",a[i][j]);
                else
                    printf(" %d",a[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}