输出:
[]
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
python解法
- 解题思路:
- 输入解析:从用户输入中解析出总容量total、数组长度length和包含球的数量的数组balls。
目标:调整balls中每个元素的数量,确保调整后的总和小于或等于total,并返回移除的球的数量数组。
二分搜索优化:
用二分法计算调整的临界值min_capacity和max_capacity,逐步缩小范围以找到满足条件的分配方案。
每次尝试一个中间值mid_capacity,计算每个桶需要移除的数量,如果结果不满足条件,则调整搜索范围。
输出结果:返回移除的球的数量数组。
def parse_input():
total, length = map(int, input().split())
balls = list(map(int, input().split()))
return total, length, balls
def calculate_removed_balls(total, balls, length):
current_sum = sum(balls)
if current_sum <= total:
return "[]"
max_capacity = max(balls)
min_capacity = total // length
result = [x - min_capacity if x > min_capacity else 0 for x in balls]
while max_capacity - min_capacity > 1:
mid_capacity = (max_capacity + min_capacity) // 2
tmp_result = [x - mid_capacity if x > mid_capacity else 0 for x in balls]
remaining_sum = current_sum - sum(tmp_result)
if remaining_sum > total:
max_capacity = mid_capacity
elif remaining_sum < total:
min_capacity = mid_capacity
result = tmp_result
else:
result = tmp_result
break
return "[" + ",".join(map(str, result)) + "]"
def main():
total, length, balls = parse_input()
print(calculate_removed_balls(total, balls, length))
if __name__ == "__main__":
main()
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
java解法
更新中
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
C++解法
更新中
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
C解法
更新中
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
JS解法
更新中
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
注意:
如果发现代码有用例覆盖不到的情况,欢迎反馈!会在第一时间修正,更新。
解题不易,如对您有帮助,欢迎点赞/收藏
评论记录:
回复评论: