华华给月月准备礼物(二分)
华华给月月准备礼物
https://ac.nowcoder.com/acm/problem/23049
题目:
二月中旬虐狗节前夕,华华决定给月月准备一份礼物。为了搭建礼物的底座,华华需要若干根同样长的木棍。华华手头上有一些长度参差不齐的木棍,他想将每根都裁剪成若干段自己想要的长度,并丢掉多余的部分。因为华华的手很巧,所以他的裁剪过程不会有任何的失误。也就是说,对于一根长度为N的木棍,华华可以精准的将它们裁剪为若干段木棍,使它们的长度之和为N。
华华不知道裁剪成多长比较好,所以干脆越长越好。不过由于华华有点强迫症,所以他希望长度为非负整数。保证所有木棍的原长也是非负整数。那么请问华华最终得到的每根木棍多长呢?
做法:
二分木棍的长度。O(n)judge,跑起来无压力。就这样无脑过了。
代码:
#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
#define debug(a) cout << #a ": " << a << endl
using namespace std;
typedef long long ll;
const int N = 2e5 + 7;
int n, k, a[N];
bool judge(int len){
int cnt = 0;
for (int i = 1; i <= n; ++i){
cnt += a[i]/len;
if (cnt >= k) return true;
}
return false;
}
int main(void){
IOS;
cin >> n >> k;
int mx = 0;
for (int i = 1; i <= n; ++i) cin >> a[i], mx = max(mx, a[i]);
int l = 1, r = mx, ans;
while (l <= r){
int mid = (l+r) >> 1;
if (judge(mid)){
ans = mid;
l = mid+1;
}else{
r = mid-1;
}
}
cout << ans << endl;
return 0;
}
查看11道真题和解析