标题:螺旋折线
如图所示的螺旋折线经过平面上所有整点恰好一次。
对于整点(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
代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//顶点的距离
int peal_distance(int x,int y,int flag) {
int tx = abs(x);
int ty = abs(y);
int distance = 0;
if (flag != 3) {
int t = tx >ty?tx:ty;
for (int i = 2*t;i > 0;i--) {
distance += 2*i;
if (flag == 1 && i == 1) {
distance -=2*t;
}
if (flag == 2 && i == 1) {
distance -= 4 * t ;
}
//flag == 4时不用修改
}
}
else {
int t = abs(x);
for (int i = 2*t-1;i > 0;i--) {
if (i != 2*t-1) {
distance += 2 * i;
}
else {
distance += i;
}
}
}
return distance;
}
int main () {
int x,y;
scanf ("%d %d",&x,&y);
int flag = 0;
if (x >= 0) {
if (y >= 0) {
flag = 1;
}
else {
flag = 4;
}
}
else {
if (y >= 0) {
flag = 2;
}
else {
flag = 3;
}
}
int distance = peal_distance(x,y,flag);
int tx = abs(x);
int ty = abs(y);
int mx = tx>ty?tx:ty;
if (flag == 1) {
if (mx > y) {
distance += mx-y;
}
else if (mx > x) {
distance -= mx - x;
}
}
if (flag == 2) {
if (mx > ty) {
distance -= mx-y;
}
else if (mx > tx) {
distance += mx -tx;
}
}
if (flag == 3) {
if (mx > ty) {
distance += mx - ty;
}
else if (mx >tx) {
distance -= mx-tx;
}
}
if (flag == 4) {
if (mx > ty) {
distance -= mx - ty;
}
else if (mx > ty) {
distance += mx -tx;
}
}
printf ("%d",distance);
}