P8647 [蓝桥杯 2017 省 AB] 分巧克力 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
暴力枚举 过70%样例
cpp
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N = 2e7+10,M = 1e3+10;
int n,k;
int h[N],w[N];
bool check(int x)
{
int cnt = 0;
for(int i=1;i<=n;i++)
{
cnt+=(h[i]/x)*(w[i]/x);
}
if(cnt>=k)return true;
else return false;
}
signed main()
{
std::ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>k;
for(int i=1;i<=n;i++)cin>>h[i]>>w[i];
int ans = 0;
for(int i=1;i<=1e5;i++)
{
if(check(i))
ans=i;
}
cout<<ans;
return 0;
}
二分
cpp
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N = 2e7+10,M = 1e3+10;
int n,k;
int h[N],w[N];
bool check(int x)
{
int cnt = 0;
for(int i=1;i<=n;i++)
{
cnt+=(h[i]/x)*(w[i]/x);
}
if(cnt>=k)return true;
else return false;
}
signed main()
{
std::ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>k;
for(int i=1;i<=n;i++)cin>>h[i]>>w[i];
int ans = -1;
int l = 0,r = 1e5;
while(l<r)
{
int mid = (l+r+1)/2;
if(check(mid))
{
l = mid;
ans = l;
}
else
{
r = mid-1;
ans = r;
}
}
cout<<ans;
return 0;
}