螺旋折线
如图所示的螺旋折线经过平面上所有整点恰好一次。
对于整点(X, Y),我们定义它到原点的距离dis(X, Y)是从原点到(X, Y)的螺旋折线段的长度。
例如dis(0, 1)=3, dis(-2, -1)=9
给出整点坐标(X, Y),你能计算出dis(X, Y)吗?
【输入格式】
X Y
对于40%的数据,-1000 <= X, Y <= 1000
对于70%的数据,-100000 <= X, Y <= 100000
对于100%的数据, -1000000000 <= X, Y <= 1000000000
【输出格式】
输出dis(X, Y)
【样例输入】
0 1
【样例输出】
3
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
思路
我先从算出(1,0)(2,0)(3,0)(4,0)的dis入手,得到以下
依次类推,得到(0,1) (0,2) (0,3)…
(-1,0)(-2,0)(-3,0)的dis
代码如下
#include<iostream>
using namespace std;
int main()
{
long long x;
long long y;
long long i;
long long dis=5;
cin >> x >> y;
if (x > 0)
{
if (x >= y)
{
for (i = 1; i < x; i++)
dis += 13 + 8 * (i - 1);//这个表达式算的是 从(0,0)到(+x,0)的距离
dis -= y;
}
if (x < y)
{
for (i = 1; i < y; i++)
dis += 13 + 8 * (i - 1);
dis -= (y+x);
}
}
if (x == 0)
{
for (i = 1; i < y; i++)
dis += 13 + 8 * (i - 1);
dis -= 2*y;
}
if (x < 0)
{
if (abs(x)>=y)
{
for (i = 1; i < abs(x); i++)
dis += 13 + 8 * (i - 1);
dis -= (4 * abs(x) - y);
}
if (abs(x)<y)
{
for (i = 1; i < y; i++)
dis += 13 + 8 * (i - 1);
dis -= (2*y-x);
}
}
cout << dis << endl;
return 0;
}