1227. Divide Chocolate

Insert picture description here
Insert picture description here
Idea: The side length a of the small chocolate must be between 1 and 100000. The answer is: find a maximum number between 1 and 100000, so that all (w[i]/a) * (h[i]/a) The sum is greater than the required number k.
Using the dichotomy to find the largest value of a is the answer.

# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;

const int N = 100010;
int n,k;
int h[N],w[N];

bool check(int mid)//判断条件
{
    
    
    int res = 0;//记录分成长度为mid的巧克力数量
    for(int i = 0;i < n;i++)
    {
    
    
        res += (h[i] / mid) * (w[i] / mid);//每块巧克力分出的数量
        if(res >= k)//大于要求数量
        {
    
    
            return true;
        }
    }
    return false;
}

int main()
{
    
    
    scanf("%d %d",&n,&k);
    for(int i = 0;i < n;i++)
    {
    
    
        scanf("%d %d",&h[i],&w[i]);
    }
    int l = 1,r = 1e5;
    while(l < r)//二分查找
    {
    
    
        int mid = (l + r + 1) / 2;
        if(check(mid))
        {
    
    
            l = mid;
        }
        else
        {
    
    
            r = mid - 1;
        }
    }
    printf("%d\n",r);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45812180/article/details/114002365