二分查找 -- 分巧克力

P8647 [蓝桥杯 2017 省 AB] 分巧克力 - 洛谷

 

思路:
    ”二分+贪心“
    由于目标是使每个人所分的的巧克力的边长尽可能大,(注意要保证公平,全部同一大小),
    设边长L*L,最小(L=1);最大min(H_i, W_i)
    每次检查当前K是否可行

    可行性检查(贪心计算):
    检查可行性(贪心计算):

对每一块巧克力 H_i * W_i,能切出的 L * L 巧克力数量是:
count = (Hi/L) * (Wi/L)   ----> 用整除
统计所有 N 块巧克力的 count 总和,若 count >= K,说明 L 可行,否则 L 太大。

'''

import sys 

def can_cut(L):
    count = sum((h // L) * (w // L) for h, w in chocolates)
    return count >= K 

def max_square_side(N, K, chocolates):
    # chocolates --> 列表 用于存储每一个巧克力的Hi和Wi(尺寸大小)
    
    left = 1
    right = max(max(h, w) for h, w in chocolates)

    while left < right:
        mid = left + (right - left + 1) // 2
        if can_cut(mid):
            res = mid
            left = mid
        else:
            right = mid - 1

    return left

N, K = map(int, sys.stdin.readline().split()) # 第一行 
chocolates = [tuple(map(int, sys.stdin.readline().split())) for _ in range (N)] # N行

print(max_square_side(N, K, chocolates))



# 上面害怕超时用sys加速了
# N, K = map(int, input().split())
# chocolates = [tuple(map(int, input().split())) for _ in range(N)]

你可能感兴趣的:(算法,python,蓝桥杯)