sicily 1302. Magic Square
2015-11-12 16:18
302 查看
1302. Magic Square
Constraints
Time Limit: 1 secs, Memory Limit: 32 MBDescription
A magic square is an arrangement of the numbers from 1 to n2 (n-squared) in an n*n matrix, with each number occurring exactly once, and such that the sum of the entries of any row, anycolumn, or any main diagonal is the same.
This problem is focused on the odd-numbered magic squares. It means that n is odd. You’ll use such a method to construct the odd-numbered magic squares. The basic rule of doing so is that one counts
diagonally upwards to the right. Let’s do it step by step.
Let’s begin in the middle of the top row with the 1. (In this example, n=3)
| 1 | |
| | |
| | |
row one column to the right of the column containing the 1.
| 1 | |
| | |
| | 2 |
row containing the 2.
| 1 | |
3 | | |
| | 2 |
instead just drop down one grid from the grid one is in presently. So the 4 will be placed directly below the 3.
| 1 | |
3 | | |
4 | | 2 |
| 1 | 6 |
3 | 5 | |
4 | | 2 |
lower left corner. That is where we want to put the 7. Unfortunately, it is already occupied by the number
b3b1
4. So there is a number in the way, and the rule is then to drop down to the square below the 6. So the 7 should be directly below the 6.
| 1 | 6 |
3 | 5 | 7 |
4 | | 2 |
8 | 1 | 6 |
3 | 5 | 7 |
4 | 9 | 2 |
Input
You will get several n (n is odd natural number, n<1,000,000) from input file. Each one is in a line by itself.And the input is terminated by a line with a single zero.
Output
For each n, you should print exactly one number in ONE line, representing the number in lower right corner of the n magic square.Sample Input
30
Sample Output
2
题目分析
求奇数阶魔方右下角的数字
不能直接模拟,因为n是百万级的,开二维数组内存爆了,
通过1318的代码查看
n=1, ans=1
n=3, ans=2
n=5, ans=9
n=7, ans=20
n=9, ans=35
n=11, ans=54
n=13, ans=77
n=15, ans=104
可以发现其通项为
a1 = 1
an = (n-1)*n/2-1
an的类型用long long存储
#include <stdio.h>
int main()
{
long long key;
while (scanf("%lld", &key)) {
if (key == 0)
break;
if (key == 1)
printf("1\n");
else
printf("%lld\n", (key-1)*key/2-1);
}
}
相关文章推荐
- PAT1007. 素数对猜想
- c语言 头文件
- CSS行高——line-height
- java 九九乘法表
- CentOS7安装iptables防火墙
- Android handler异步处理简单例子
- Transform(变换)
- maven deploy 401错误
- java 九九乘法表
- 两个应用之间的跳转以及传值
- ios AFHTTPSessionManger下载补充
- 通过HttpClient获取服务器接口json数据已及解析
- String、StringBuffer与StringBuilder之间区别
- RSA的公钥和私钥
- oh-my-zsh主题
- win10屏幕键盘快捷键设置技巧(五种方法) win10怎样打开屏幕键盘
- 【VB.NET】——ADO与ADO.NET区别
- 滚动条美化jquery插件nicescroll的使用
- PAT1006. 换个格式输出整数
- 各种软件查看版本