Contest02-4 Spiral
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
Given an odd number n, we can arrange integers from 1 to n*n in the shape of a spiral. The Figure 1 below illustrates the spiral made by integers from 1 to 25.
As we see above, each position in the spiral corresponds to a unique integer. For example, the number in row 1, column 1 is 21, and integer 16 is in row 5, column 2. Now, given the odd number n(1<=n<=32768), and an integer m(1<=m<=n*n), you should write a program to find out the position of m.
As we see above, each position in the spiral corresponds to a unique integer. For example, the number in row 1, column 1 is 21, and integer 16 is in row 5, column 2. Now, given the odd number n(1<=n<=32768), and an integer m(1<=m<=n*n), you should write a program to find out the position of m.
输入
The first line of the input is a positive integer T(T<=20). T is the number of the test cases followed. Each case consists of two integer n and m as described above.
输出
For each case, output the row number and column number that the given integer is in, separated by a single whitespace. Please note that the row and column number are both starting from 1.
示例输入
3 3 9 5 21 5 16
示例输出
1 3 1 1 5 2
提示
题意:根据给出的螺旋数的规律,求给定m在n*n矩阵中的行和列
规律:
可以发现最中间的1的坐标一直都是(n/2+1,n/2+1),而从1开始,一直都是向右,向下,向左,向上这四个方向的循环,4个方向的数的个数为1,1,2,2,3,3,4,4,5,5,······n-1,n-1,n-1,根据这些可以得到每个方向每个数的改变情况,从而得到给定m坐标
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
int T;
int n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
int i=n/2+1;
int j=n/2+1;
int s=1;
int e;
int a=1;
int flag=0;
if(m==1)
{
printf("%d %d\n",i,j);
continue;
}
while(s<n)
{
if(a+s<m)
{
a+=s;
j+=s;
}
else
{
j+=m-a;
a=m;
flag=1;
break;
}
if(a+s<m)
{
a+=s;
i+=s;
}
else
{
i+=m-a;
a=m;
flag=1;
break;
}
s++;
if(a+s<m)
{
a+=s;
j-=s;
}
else
{
j-=m-a;
a=m;
flag=1;
break;
}
if(a+s<m)
{
a+=s;
i-=s;
}
else
{
i-=m-a;
a=m;
flag=1;
break;
}
s++;
}
s--;
if(!flag)
{
j+=m-a;
a=m;
}
printf("%d %d\n",i,j);
}
return 0;
}