选靓号 拼多多[编程题](python 95%解)

在这里插入图片描述
在这里插入图片描述
95%通过率

l1 = input().split(' ')
original_str = input()
strl2 = list(original_str)
l2 = [int(val) for val in strl2]
n,k = int(l1[0]),int(l1[1])
#一共n位
#需要有k个相同
all_val = []
diff = 0
for each in l2:
    if each not in all_val:
        all_val.append(each)
        diff += 1
dp = []
index_list = []
for each_val in all_val:
    tempres = []
    for each_number in l2:
        tempres.append(abs(int(each_number)-int(each_val)))
    dp.append(tempres)
candidate = {}
mini = sum(l2)
miniindex = []
for i,each_list in enumerate(dp):
    templist = sorted(each_list)
    temp_sum = sum(templist[:k])
    if mini >= temp_sum:
        mini = temp_sum
        if temp_sum in candidate:
            candidate[temp_sum].append(each_list+[all_val[i]]+[templist[k]])
        else:
            candidate = {}
            candidate[temp_sum] = [each_list + [all_val[i]]+[templist[k]]]
#miniindex是all_val中替换代价最小的靓号一位数
for only_cost in candidate:
    all_lists = candidate[only_cost]
print(only_cost)
minimum = None
for each_list in all_lists:
    #each_list的前n位是代价数组 第n+1位是调整的目标一位数 第n+2位是所耗的最大的单位代价
    this_list = each_list[:n]
    target = each_list[-2]
    maxcost = each_list[-1]
    thisstr = original_str
    temp_sum = 0
    rem = []
    has_used = 0
    for i,val in enumerate(this_list):
        if val < maxcost:
            thisstr = thisstr[:i] + str(target) + thisstr[i+1:]
            has_used += 1
        elif val == maxcost:
            temp_sum += 1
            rem.append(i)
    index = 0
    while has_used < k:
        this_ob = thisstr[rem[index]]
        if int(this_ob) > target or (int(this_ob) < target and len(rem[index+1:]) < k - has_used):
            #print(len(rem[index+1:]),temp_sum-changed)
            thisstr = thisstr[:rem[index]] + str(target) + thisstr[rem[index]+1:] 
            index += 1
            has_used += 1
        elif int(this_ob) < target and len(rem[index+1:]) >= k - has_used:
            index += 1

    if minimum == None or thisstr < minimum:
        minimum = thisstr
print(minimum)

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/107748541
95
今日推荐