用python写算法求最少的距离

img

img


img

这个算法要用python3来写,还需要主义下面N,L和M的取值范围,确保在不同的情况下都能跑出来。这是一道之前澳洲编程竞赛的一道样板题,希望大家可以集思广益一下,谢谢

试了一下:

N,M,L = map(int, input().split())
stores = set(map(int,input().split()))
houses = set(map(int,input().split()))
pamphlet = list(map(int,input().split()))
for R in range(L):
    res = []
    for i in houses:
        temp = len(stores & set(range(i-R, i+R+1)))
        res.append(temp)
        if temp not in pamphlet or res.count(temp)>pamphlet.count(temp):
            break
    else:
        if sorted(res) == sorted(pamphlet):
            print(R)
            break
else:
    print(-1)

给出的三个测试结果都正确:

4 5 15
1 5 8 9
3 6 8 10 14
0 2 2 3 3
3

3 2 6
1 3 5
2 6
1 3
-1

4 3 14
1 6 10 14
3 9 13
1 1 1
2