【每日一题】华华给月月准备礼物
华华给月月准备礼物
http://www.nowcoder.com/questionTerminal/9963334321e64e61a397b262708e4f65
只有长度大于等于x的木棍才能切出长度为x的木棍,而可以切出木棍长为x的木棍k条,那么长为x-1的木棍也至少能切除k条,具有单调性,二分找最大值,二分起点为1,终点为原本木棍中的mx;
ans初始为-1只能过90%,我的理解是会存在无解的情况,但题目输出要求是一个非负整数,所有应该将ans初始为0
#include <cstdio> #include <algorithm> using namespace std; typedef long long ll; const ll inf = 1e12; const int N = 2e5+10; int n; ll k,a[N]; bool check(ll x){ int pos = lower_bound(a,a+n,x)-a; ll res = 0; for(int i = pos;i < n;i++){ res += (a[i]/x); } return res >= k; } int main(){ scanf("%d%lld",&n,&k); for(int i = 0;i < n;i++){ scanf("%lld",a+i); } sort(a,a+n); ll l = 1,r = a[n-1]; ll ans = 0; while(l <= r){ ll mid = l+r>>1; if(check(mid)){ ans = mid; l = mid+1; }else r = mid-1; } printf("%lld\n",ans); return 0; }