magic square

来源:互联网 发布:好听的中文歌 知乎 编辑:程序博客网 时间:2024/05/18 02:43
 

Magic Square

Time Limit: 3000MS Memory Limit: Unknown 64bit IO Format: %lld & %llu

[Submit] [Go Back] [Status]

Description

If you have good observations skills, you may found that building a Magic Square is simple. A Magic Square has only an odd numberN of rows and columns. For this problem you could expect the values to be3$ \le$N$ \le$15. A Magic Square is created by integer numbers in the range from 1 to N2, with a peculiar property, the ``sum of the numbers" in each row, column and diagonal is the same value.


For example the case for n = 3 is:

M. Square                Rows          Columns       Diagonals 8 1 6                   8+1+6 = 15    8+3+4 = 15    8+5+2 = 15 3 5 7                   3+5+7 = 15    1+5+9 = 15    4+5+6 = 15 4 9 2                   4+9+2 = 15    6+7+2 = 15


Hint: 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.

Input

A file with several lines, each line has the value of n.

Output

For each input line, print N and the sum in the first line, followed by the magic square. To see a nice looking square, take into account the maximum length in characters ofN2 and print each number with the maximum length preceded by one space or blank character. Print one line between squares.

Sample Input

35

Sample Output

n=3, sum=15 8 1 6 3 5 7 4 9 2n=5, sum=65 17 24  1  8 15 23  5  7 14 16  4  6 13 20 22 10 12 19 21  3 11 18 25  2  9

数组从1开始

1的位置,当N为奇数时候,在正中间,N为偶数的时候,在中间左边,所以1的位置就是(N+1)/2;

2的位置,在1的下一列最后一行

3的位置,若右上角有数或到边缘了,则在2的上一行最左边的一列

4的位置,若右上角有数或到边缘,则在3的下一行同一列的位置,否则在斜边缘

同理。。。。

memset(board,0,sizeof(board));        h=1;l=(N+1)/2;//算1的位置        for(k=1;k<=N*N;k++){if(board[h][l]==0){board[h][l]=k;h=(h-1)%N; if(h==0) h=N;l=(l+1)%N; if(l==0) l=N;if(board[h][l]!=0) {h=(h+2)%N; if(h==0) h=N;l=(l-1)%N; if(l==0) l=N; }}else{board[(h=h+1)][l]=k;//若该数不再表格边缘,跳到下一行}


 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 台式电脑网页打不开怎么办 电脑网页很多都打不开怎么办 qq发送不了位置怎么办 qq无法找到入口怎么办 玩游戏总是掉怎么办 ipad所有按键失灵怎么办 手机启动器停止运行怎么办 安卓版泰拉瑞亚联机失去连接怎么办 吃鸡安装不了怎么办 obb文件丢失了怎么办 dnf登录闪退怎么办 泰拉瑞亚地图找不到备份怎么办 服务器没远程管理卡怎么办 tplink上不了网怎么办 键盘端口坏了怎么办 小米路由dns错误怎么办 电脑内存性能低怎么办 nas硬盘坏了怎么办 360安装环境异常怎么办 连接不上服务器怎么办 路由器被绑定mac怎么办 mac地址绑定失败怎么办 触摸屏忘了密码怎么办? 小区高层水压低怎么办 高层楼房水压不够怎么办 热水器温度太高怎么办 热水器出热水小怎么办 天然气热水器水压不够怎么办 热水器水变小了怎么办 液压齿轮泵没力怎么办 gps总是浮点解怎么办 电源要做到稳压怎么办 变压器输出电压低怎么办 变压器输出电压高怎么办 家里空调带不动怎么办 小天才定位不准怎么办 伐木锯链条不出油怎么办 角磨机切割片卸不下来怎么办 油泵电机声音大怎么办 汽车油泵声音大怎么办 水泵电机噪音大怎么办