第七题:螺旋折线
如图所示的螺旋折线经过平面上所有整点恰好一次。 对于整点(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 螺旋折线 { /** * @param args */ static int sum=0; static int dir[][]={{0,1},{1,0},{0,-1},{-1,0}}; public static void main(String[] args) { Scanner sc=new Scanner(System.in); String s[]=sc.nextLine().split("\\s+"); int x=Integer.valueOf(s[0]); int y=Integer.valueOf(s[1]); int xs=-1; int ys=0; int f=0; for (;;) { xs=xs+dir[f][0]; ys=ys+dir[f][1]; sum++; if(xs==x && ys==y){ break; } if(xs<0 && ys<0){ if(Math.abs(ys)*2==Math.abs(xs)){ f=(f+1)%4; } }else { if(Math.abs(ys)==Math.abs(xs)){ f=(f+1)%4; } } } System.out.println(sum+1); } }