先上题目:
Description
Time Limit: 3000 MS Memory Limit: 65536 K
Description
GLC has developed an algorithm to map each lattice point in the 2-d catesian coordinates to a nature number. For example: (0, 0) -> 0 (1, 0) -> 1 (1, 1) -> 2 (0, 1) -> 3 (-1, 1)-> 4 ... and so on. If we connect every two adjacent points by a segment, we get a spiral line which starts at (0, 0). Now, given a point on the plane, you are to find the nature number it mapped to.
Input
The first line of input is the number of test case. For each test case, thers is only one line contains two number x , y ( |x|, |y| <= 10,000 ).
Output
for each test case, output the answer in one line.
Sample Input
2 2 3 3 4
Sample Output
31 57
题意:以(0,0)点为起点(零号点),作逆时针回旋矩阵,给出坐标,求出是第几个数。
直接模拟。根据分析,可以发现想一个方向前进的长度变化是每转两次方向加一。对于要判断目标点是不是在某一段上,我们需要判断这某一段的端点是不是都相等而且等于目标点的其中一个坐标,然后另一个坐标在端点对应坐标之间。不过注意端点的坐标大小不一定是从小到大排的,所以需要分情况讨论。然后统计一下中间的移动步数就可以了。
上代码:
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 5 int cy[]={0,1,0,-1}; 6 int cx[]={1,0,-1,0}; 7 int a,b; 8 int u; 9 inline bool check(int l,int m,int r){ 10 if(l<=m && m<=r){ 11 u=m-l; 12 return 1; 13 } 14 if(r<=m && m<=l){ 15 u=l-m; 16 return 1; 17 } 18 return 0; 19 } 20 21 int deal(){ 22 int c,i,x,y,x0,y0,ans; 23 c=0,i=0; 24 x=y=0; 25 ans=0; 26 while(1){ 27 i++; 28 for(int j=0;j<2;j++){ 29 y0=y+cy[c]*i; 30 x0=x+cx[c]*i; 31 c=(c+1)%4; 32 //printf("%d %d ",x0,y0); 33 if(x==x0 && a==x && check(y,b,y0)){ 34 ans+=u; 35 return ans; 36 }else if(y==y0 && y0==b && check(x,a,x0)){ 37 ans+=u; 38 return ans; 39 } 40 ans+=i; 41 y=y0; 42 x=x0; 43 } 44 } 45 return -1; 46 } 47 48 int main() 49 { 50 int t; 51 //freopen("data.txt","r",stdin); 52 scanf("%d",&t); 53 while(t--){ 54 scanf("%d %d",&a,&b); 55 printf("%d ",deal()); 56 } 57 return 0; 58 }