您的位置:首页 > 其它

螺旋的矩阵

2015-10-31 23:25 309 查看
螺旋的矩阵
Time Limit: 1000 MSMemory Limit: 32768 K
Total Submit: 23(16 users)Total Accepted: 14(14 users)Rating:Special Judge: No
Description
给出一个奇数 n,我们可以把数字 1 到 n*n 放到一个螺旋的矩阵中。

下图给出了从1到25的放法:

1 2 3 4 5

---------------------

1| 21 22 23 24 25

2| 20 7 8 9 10

3| 19 6 1 2 11

4| 18 5 4 3 12

5| 17 16 15 14 13

正如我们看到的,矩阵中的每个位置都对应一个唯一的整数,例如第一行第一列是一个21,第5行第2列是一个16。

现在,给出一个整数 n(1<=n<=32768),和一个整数m(1<=m<=n*n),你需要输出整数 m的位置。

Input
第一行是一个整数T,表示数据的组数,接下来的T行每行两个整数n, m。

Output
第一行是一个整数T,表示数据的组数,接下来的T行每行两个整数n, m。

Sample Input
3

3 9

5 21

5 16

Sample Output
3

3 9

5 21

5 16

Source
2014.11.30新生赛-正式赛
找规律,水。。。。

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long LONG;
int main()
{
int T;
while(~scanf("%d",&T))
{
while(T--)
{
LONG n,m;
scanf("%ld%ld",&n,&m);
LONG s=sqrt(m*1.0);
LONG s1=s*s;
LONG x,y;
if(s%2==1)
{
x=1+(n-s)/2,y=s+(n-s)/2;
if(s1==m)
{
printf("%ld %ld\n",x,y);
continue;
}
y++;
s1++;
if(s1==m)
{
printf("%ld %ld\n",x,y);
continue;
}
int i;
int key=0;
for(i=0;i<s;i++)
{
s1++;
x++;
if(s1==m)
{
key=1;
printf("%ld %ld\n",x,y);
break;
}
}
if(key)
{
continue;
}
for(i=0;i<s;i++)
{
s1++;
y--;
if(s1==m)
{
printf("%ld %ld\n",x,y);
break;
}
}
}
else
{
x=n-(n-s)/2;
y=(n-s)/2+n%2+1;
//    cout<<x<<" "<<y<<endl;
if(s1==m)
{
printf("%ld %ld\n",x,y);
continue;
}
y--;
s1++;
if(s1==m)
{
printf("%ld %ld\n",x,y);
continue;
}
int i;
int key=0;
for(i=0;i<s;i++)
{
x--;
s1++;
if(s1==m)
{
key=1;
printf("%ld %ld\n",x,y);
break;
}
}
if(key)
{
continue;
}
for(i=0;i<s;i++)
{
y++;
s1++;
if(s1==m)
{
printf("%ld %ld\n",x,y);
break;
}
}
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: