python练习题:士兵的生气指数

阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴

img

img

img

我选择干掉将军

m,n = input().split(' ')
a = [int(i) for i in input().split(' ')]
m = int(m)
n = int(n)
x = sum(a) - m  # 缺多少金币,平均分给每个人最终的生气指数是最小的,但由于每个人能分到的数量是整数
print(x%n*((x//n+1)**2)+ (n-x%n)*((x//n)**2))  # n-x%n个人缺x//n个金币,x%n个人缺x//n+1个金币,所以生气指数为人数 *缺金币数**2
p = input().split(' ')
m = int(p[0])
n = int(p[1])
a = [int(x) for x in input().split(' ')]
b = a.copy()
s = sum(a) - m  #差的金币数量,要平均分摊给每个士兵
i = 0
while s>0:
    if b[i]>0:
        b[i] -= 1
        s -= 1
    i = (i+1)%n
c = sum((y-x)**2 for x,y in zip(a,b))
print(c)

m = int(input())
n = int(input())

a = input().split(' ')

a = [int(i) for i in a]
x = (sum(a) - m) // n
y = (sum(a) - m) % n
res = [0] * n
for i in range(1, y+1):
    res[i-1] = 1
ans = sum((x+i)**2 for i in res)
print(ans)

缺m个金币,共n个士兵,平均分配时,生气指数最小。
但士兵分到的金币数量是整数,因此会多出一些,再分给其中的一些士兵。
如下图:
img

a, b = input('总金币、总士兵:').split(' ')
c = input('每个士兵期望的金币:').split(' ')
m = sum(c) - a  # 缺的金币
n = b           # 总士兵数
print( (n - m % n) * (m // n) ** 2 + (m % n) * (m // n + 1) ** 2 )