Divide Chocolate - Divide

Original title link

Share Chocolate 2017 Blue Bridge
Children's Day, K children visited Xiaoming's house.
Xiao Ming took out a collection of chocolates to entertain the children.
Xiaoming has a total of N pieces of chocolate, of which the i-th piece is H i × Wi i Hi × WiHi×A rectangle composed of squares of Wi . To be fair, Xiao Ming needs to cut out K pieces of chocolate from these N pieces of chocolate and distribute them to the children.
The cut chocolate needs to meet:

  • shape is square
  • Side lengths are the same size as integers

For example, a 6×5 piece of chocolate can be cut into 6 pieces of 2×2 chocolate or 2 pieces of 3×3 chocolate.

Of course, the children all want to get as big a chocolate as possible. Can you help Xiao Ming calculate the maximum side length?

binary search

Divide the side length from 1 to the given maximum boundary
By dividing the side length of the chocolate, use int to directly round down, and the product can get the number of chocolates that can be divided

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
int n, k;
vector<PII> v;

bool check(int a) {
    
     // 保证了边长相同,且为正方形
    int res = 0;
    for (auto t: v) {
    
     
        res += ((t.x / a) * (t.y / a)); // 计算按边长a可以分的巧克力数
        if (res >= k) return true;
    }
    return false;
}

int main() {
    
    
    scanf("%d%d", &n, &k);
    int r = 0;
    for (int i = 0; i < n; i++) {
    
    
        int h, w;
        scanf("%d %d", &h, &w);
        v.push_back({
    
    h, w});
        r = max(r, h);
        r = max(r, w);
    }
    int l = 1;
    while (l < r) {
    
    
        int mid = l + r + 1 >> 1;
        if (check(mid)) l = mid;
        else r = mid - 1;
    }
    cout << l << endl;
    
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324213220&siteId=291194637