版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/86522727
Description
给定一个正整数n,现在构造一个n*n的蛇形矩阵,矩阵每个格子内填入一个数字。矩阵右上角填入1,左下角填入n*n,从1..n*n依次填入数字的顺序为(1,n)-->(1,n-1)-->(2,n)-->(3,n)-->(2,n-1)-->(1,n-2)-->...-->(n,n)。譬如说4*4的蛇形矩阵是:
现在给出n,求n*n的蛇形矩阵中第x行y列的数字是什么。
Input
一行,三个整数n,x,y。
Output
一行,一个整数,表示n*n的蛇形矩阵中第x行y列的数字。
4 3 1
-
Sample Input
14
-
Sample Output
HINT
对40%的数据,n<=100。
对100%的数据,n<=30000。
接下来,正解(有点复杂): (O(1)过9亿)
#include <iostream>
#include <cstdio>
using namespace std;
int main(void)
{
int n, x, y, dis, res;
scanf("%d%d%d", &n, &x, &y);
y = n - y + 1; // 矩阵左右翻转
dis = x + y - 1; // 离(1,1)的距离
if (dis <= n) // 在矩阵的左上部
{
res = dis * (dis - 1) >> 1; // 等差数列公式求前面格子的个数
if (dis & 1) // 分两种情况,奇偶有不同的方向
{
printf("%d", res + y);
}
else
{
printf("%d", res + x);
}
}
else // 在矩阵的右下部
{
res = n * n - ((n + n - dis + 1) * (n + n - dis) >> 1); // 同样使用等差数列公式计算这一斜线之前的个数
if (dis & 1) // 同上
{
printf("%d", res + n - x + 1);
}
else
{
printf("%d", res + n - y + 1);
}
}
return 0;
}