题目描述
如图所示的螺旋折线经过平面上所有整点恰好一次。
对于整点(X, Y),我们定义它到原点的距离dis(X, Y)是从原点到(X, Y)的螺旋折线段的长度。
例如dis(0, 1)=3, dis(-2, -1)=9
给出整点坐标(X, Y),你能计算出dis(X, Y)吗?
输入格式
X 和 Y
输出格式
输出dis(X, Y)
样例输入
0 1
样例输出
3
解题思路
本来看的C语言网的,没提示数据大小,直接用的模拟,四个循环表示往四个方向走,走得步长是length,cnt表示方向个数,可以看到没换两次方向,length+1,distance表示总距离
代码:
代码略复杂,最后过了一半的样例,做的时候没想到找规律
import os
import sys
x_0,y_0 = map(int,input().split())
# print("x_0:",x_0,"y_0:",y_0)
# 四个方向
# x,y 是坐标
# cnt 是拐的次数,2次后长度+1
# 初始长度length
x = 0
y = 0
length = 1
cnt = 0
distance = 0 # 记录总距离
i = 0 # 小于length继续走
flag = True
# 特殊情况 0 0
if x_0 == 0 and y_0 == 0:
print(0)
flag = False
while flag:
while i < length:
i+=1
x-=1
distance+=1
if x == x_0 and y == y_0:
print(distance)
flag = False
break
if cnt == 2:
length+=1
cnt=0
#print("←","i",i,"(x:",x,"y:",y,")cnt:",cnt,"diatance",distance,"length",length)
i=0
cnt+=1
if not flag: break
while i < length:
y+=1
i+=1
distance+=1
if x == x_0 and y == y_0:
print(distance)
flag = False
break
if cnt == 2:
length+=1
cnt=0
#print("↑","i",i,"(x:",x,"y:",y,")cnt:",cnt,"diatance",distance,"length",length)
i=0
cnt+=1
if not flag: break
while i < length:
i+=1
x+=1
distance+=1
if x == x_0 and y == y_0:
print(distance)
flag = False
break
if cnt == 2:
length+=1
cnt=0
#print("→","i",i,"(x:",x,"y:",y,")cnt:",cnt,"diatance",distance,"length",length)
i=0
cnt+=1
#print("注意!!","i",i,"(x:",x,"y:",y,")cnt:",cnt,"diatance",distance,"length",length)
if not flag: break
while i < length:
i+=1
y-=1
distance+=1
if x == x_0 and y == y_0:
print(distance)
flag = False
break
if cnt == 2:
length+=1
cnt=0
#print("↓","i",i,"(x:",x,"y:",y,")cnt:",cnt,"diatance",distance,"length",length)
i=0
cnt+=1
if not flag: break
其他人的解法:
看到洛谷的一个题解:P8668 [蓝桥杯 2018 省 B] 螺旋折线 题解