天天看点

Greedy Algorithms: Greedy Florist

Greedy Algorithms: Greedy Florist
#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the getMinimumCost function below.
#my own solution
def getMinimumCost0(k, c):
    if k>=len(c):
        return sum(c)
    
    s=sorted(c)
    n=len(s)//k+1
    cost=0
    
    for i in range(n):
        m=len(s)
        if m<k: #最后个数小于k了
            cost+=sum(s)*(i+1)
            return cost
        cost+=sum(s[m-k:])*(i+1) 
        s=s[:m-k]
    return cost

# a better solution. more concise.
def getMinimumCost(k, flowers):
    res = 0
    cnt = 0

    flowers = sorted(flowers, key=lambda x: -x)#降序排列
    
    for el in flowers:
        res += el * (1 + cnt//k)
        cnt += 1
        
    return res


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nk = input().split()

    n = int(nk[0])

    k = int(nk[1])

    c = list(map(int, input().rstrip().split()))

    minimumCost = getMinimumCost(k, c)

    fptr.write(str(minimumCost) + '\n')

    fptr.close()