C++ Divided Chocolate (Binary Search)

On Children's Day, K children visited Xiao Ming's house as guests.
Xiao Ming took out a collection of chocolates to entertain the children.
Xiao Ming has N pieces of chocolate in total, of which the i-th piece is a rectangle composed of Hi×Wi squares. To be fair, Xiao Ming needs to cut out K pieces of chocolate from the N pieces of chocolate to share with the children.
The cut chocolate needs to meet: the
shape is a square, the side length is an integer, and the
size is the same.
For example, a piece of 6×5
chocolate can cut out 6 pieces of 2×2 chocolate or 2 pieces of 3×3 chocolate.
Of course, the children all hope that the chocolate they get is as large as possible. Can you help Xiao Ming calculate the maximum side length?
Input format The
first line contains two integers N and K. Each of the following N lines contains two integers Hi and Wi.
Enter to ensure that each child can get at least a 1×1 chocolate.
Output format
Output the maximum possible side length of the cut square chocolate.
Data range
1≤N,K≤105,1≤Hi,Wi≤105
Input example:
2 10
6 5
5 6
Output example:
2

AC code:

#include<stdio.h>
#include<algorithm>

using namespace std;

struct rect//记录每块巧克力长和宽
{
    
    
    int h,w;
    bool operator<(rect &r)//排序规则
    {
    
    
    	//较小边更小者排前面
        return min(h,w)<min(r.w,r.h);
    }
}rect[100010];

int n,k;

int check(int x)//计算边长为x时能分几块巧克力
{
    
    
    int sum=0;
    for(int i=0;i<n;++i)
    {
    
    
        sum+=(rect[i].w/x)*(rect[i].h/x);
    }
    return sum;
}

int main()
{
    
    
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;++i)
    {
    
    
        scanf("%d%d",&rect[i].h,&rect[i].w);
    }
    sort(rect,rect+n);//排序
    int l,r,mid;
    int ans=1;//答案至少为1
    //采用左开右开区间写法
    l=0;//答案至少为1,则左边界为1-1
    r=min(rect[n-1].w,rect[n-1].h)+1;//选max肯定一块也分不了,所以选min
    //因为右开,所以还要+1
    int sum;//决策为mid时能分几块
    while(l+1!=r)
    {
    
    
        mid=l+((r-l+1)>>1);
        sum=check(mid);
        if(sum>=k){
    
    //够分,探索更大的边是否够
            l=mid;
            ans=max(ans,mid);
        }
        else {
    
    //不够分,边长减小
            r=mid;
        }
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108785080