The difference between the
two templates for topic y : see whether mid is placed in l or r
int bsearch_1(int l, int r)
{
while (l < r)
{
int mid = l + r >> 1;
if (check(mid)) r = mid; // check()判断mid是否满足性质
else l = mid + 1;
}
return l;
}
int bsearch_2(int l, int r)
{
while (l < r)
{
int mid = l + r + 1 >> 1;
if (check(mid)) l = mid;
else r = mid - 1;
}
return l;
}
Idea: Use dichotomy to find the most suitable number of divisions. If there is more chocolate, change mid to l, and if less, change mid to r-1.
If you find that the answer is 1 more than the actual one when doing a dichotomous question, you can directly subtract 1 when outputting the answer
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, k;
int h[N], w[N];
bool check(int mid)
{
int res = 0;
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)//y总的第二经典模板
{
int mid = l + r +1 >> 1;
if (check(mid)) l = mid;
else r = mid -1;
}
printf("%d\n", r);
return 0;
}