标题:螺旋折线
如图p1.pgn所示的螺旋折线经过平面上所有整点恰好一次。
对于整点(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
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
不要使用package语句。不要使用jdk1.7及以上版本的特性。
主类的名字必须是:Main,否则按无效代码处理。
import java.util.Scanner;
public class t7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
int resultX = 0;
int resultY = 0;
int count = 0;
int dirX = -1;
int dirY = 1;
for (int i = 1 ; ; i++) {
int cur = i;
if (resultX == x && resultY == y){
System.out.println(count);
return;
}
while (cur-- != 0) {
resultX += dirX;
count++;
if (resultX == x && resultY == y) {
System.out.println(count);
return;
}
}
cur = i ;
while (cur-- != 0) {
resultY += dirY;
count++;
if (resultX == x && resultY == y) {
System.out.println(count);
return;
}
}
dirX = -dirX;
dirY = -dirY;
}
}
}