蓝桥杯 分巧克力

发布时间 2023-08-02 18:59:33作者: 完美二叉树

https://www.lanqiao.cn/problems/99/learning/?page=3&first_category_id=1&sort=students_count&second_category_id=3

暴力方法

N, K = map(int, input().split())
chocolates = [[int(n) for n in input().split()] for _ in range(N)]

max_size = 1

for size in range(2, max([max(c) for c in chocolates])):
    # 计算边长为size的时候,能分成几块
    num = sum([(c[0] // size) * (c[1] // size) for c in chocolates])
    # print(size, num)
    # 如果够分,就更新
    if num > K:
        max_size = size

print(max_size)

二分查找优化

N, K = map(int, input().split())  
chocolates = [[int(n) for n in input().split()] for _ in range(N)]  
max_len = max([max(c) for c in chocolates])  
left, right = 0, max_len + 1  
while left + 1 != right:  
    middle = (left + right) // 2  
    # 在middle长度下,可以分的块数  
    num = sum([(c[0] // middle) * (c[1] // middle) for c in chocolates])  
    if num >= K:  
        left = middle  
    else:  
        right = middle  
print(left)