我不知道是否有一个简明的数学方程可以推导出你想要的东西,但我有一个解决方案,可以在每个查询的 O(1) 时间内计算你想要的东西。没有你想要的循环。
我的方法:
(i) 对于任何给定的点 (x,y),找到位于边长平方 (2*a-1) 中的点的数量,其中 a = Max( |x|, |y| ) .这些是内部点。即位于所有螺旋中的点数,不包括当前螺旋。
这不过是 ( 2*a -1 )*( 2*a -1 )
例如:考虑下图:
y
|
|
16 15 14 13 12
17 4 3 2 11
-- 18 5 0 1 10 --- x
19 6 7 8 9
20 21 22 23 24
|
|
对于点 ( 2,1 ),a = 2。内部点,这里标记为 0, 1, 2, 3, 4, 5, 6, 7, 8 - 边长为 3 的正方形
(ii) 现在计算位于当前螺旋线上的点。螺旋有 4 个“角”点 -
(a) 起点(当前螺旋开始的地方)
(b) 点 (a, a)
(c) 点 (-a, a)
(d) 点(-a, -a)
所以,我计算了位于每对这样的元素之间的元素数量 [即,在 (a) 和 (b)、(b) 和 (c)、(c) 和 (d) 之间],这样所有这些落在螺旋序列中所需的输入点之前。这可以通过点坐标的简单减法来完成。
这个值加上内部点数将为您提供所需的答案。
我不确定我是否已经非常清楚地解释了这一点。如果您需要任何澄清或进一步解释,请告诉我。
附件是我为测试我的逻辑而编写的 JAVA 代码。很抱歉,它不是很优雅,但它可以工作:P
import java.io.IOException;
import java.util.Scanner;
class Pnt
{
int x, y;
public Pnt( int _x, int _y )
{
x = _x;
y = _y;
}
}
public class Spiral
{
static int interior( Pnt p ) // returns points within interior square of side length MAX( x, y ) - 1
{
int a = Math.max( Math.abs( p.x ), Math.abs( p.y ));
return ( 2*a - 1 )*( 2*a - 1 );
}
static Pnt startPnt( Pnt p ) // first point in that spiral
{
int a = Math.max( Math.abs( p.x ), Math.abs( p.y ));
// last pnt in prev spiral = [ a-1, -( a-1 ) ]
// next pnt = [ a, -( a-1 ) ]
return new Pnt( a, -( a-1 ));
}
static int offSetRow1( Pnt pStart, Pnt p )
{
return ( p.y - pStart.y ) + 1;
}
static int solve( Pnt curr )
{
// check location of curr
// It may lie on 1st row, 2nd row, 3rd or 4th row
int a = Math.max( Math.abs( curr.x ), Math.abs( curr.y ));
int off=0;
int interiorCnt = interior( curr );
Pnt start = startPnt( curr );
if( ( curr.x == a ) && ( curr.y >= start.y ) ) // row 1
{
off = offSetRow1( start, curr );
return off+interiorCnt;
}
if( curr.y == a ) // row 2
{
Pnt start2 = new Pnt( a, a );
int off1 = offSetRow1( start, start2 );
// now add diff in x-coordinates
int off2 = start2.x - curr.x;
off = off1 + off2;
return off+interiorCnt;
}
if( curr.x == -a ) // row 3
{
Pnt start2 = new Pnt( a, a );
int off1 = offSetRow1( start, start2 );
// now add diff in x-coordinates
Pnt start3 = new Pnt( -a, a );
int off2 = start2.x - start3.x;
// now add diff in y co-ordinates
int off3 = start3.y - curr.y;
off = off1 + off2 + off3;
return off+interiorCnt;
}
else // row 4
{
Pnt start2 = new Pnt( a, a );
int off1 = offSetRow1( start, start2 );
// now add diff in x-coordinates
Pnt start3 = new Pnt( -a, a );
int off2 = start2.x - start3.x;
// now add diff in y co-ordinates
int off3 = start3.y - curr.y;
Pnt start4 = new Pnt( -a, -a );
// add diff in x co-ordinates
int off4 = curr.x - start4.x;
off = off1 + off2 + off3 + off4;
return interiorCnt + off;
}
}
public static void main( String[] args ) throws IOException
{
Scanner s = new Scanner( System.in );
while( true )
{
int x = s.nextInt();
int y = s.nextInt();
Pnt curr = new Pnt( x, y );
System.out.println( solve( curr ));
}
}
}