思路间代码注释
def minDistance():
'''
想法:
如果项链是一条线,不是环,那么线上各珍珠最小移动距离为到中位数的移动距离,
所以遍历项链的n个位置,剪断,将项链拉成一条线,此时求最短移动距离,然后取最短
'''
l,n=list(map(int,input().strip().split()))
pos=list(map(int,input().strip().split()))
def __mindistance(onepos):
'''每条线的最短移动距离'''
if n%2==0 and n>2:
midNum1=onepos[n//2]
midNum2 = onepos[n//2 -1]
steps1 = 0
steps2 = 0
for num in onepos:
steps1 += abs(num - midNum1)
steps2 += abs(num - midNum2)
pianyi = 0
for i in range(n//2 -1):
pianyi += i
steps = min(steps1, steps2)
return steps - pianyi * 2 - n
else:
zhongweishu = onepos[n // 2]
steps = 0
for num in onepos:
steps += abs(num - zhongweishu)
pianyi = 0
for i in range(n // 2):
pianyi += i
return steps - pianyi * 2 - n+1
minstep=sum(pos)
for i in range(l):
pos_temp=[po-i if po>=i else l-i+po for po in pos]
pos_temp.sort()
step=__mindistance(pos_temp)
if step<minstep:
minstep=step
return minstep