AtCoder Beginner Contest 227D题Project Planning(二分)

题目链接
AtCoder Beginner Contest 227D题Project Planning(二分)_第1张图片
考虑二分答案,如何check呢?
假设答案为mid ,那么相当于要摆放mid个盒子,每个盒子要有K个不同的小球,因为同种小球不能摆在一起,故每种小球只能摆放min(mid,a[i]) 个
填充的思想,直到填满K层 记为true

 #include
#include
#include
#include
#include
#include
#include
#include 
#include 
#include 
#define ll long long
#define int long long
#define inf 0x3f3f3f3f
#define mods 1000000007
#define modd 998244353
#define PI acos(-1)
#define fi first
#define se second
#define lowbit(x) (x&(-x))
#define mp make_pair
#define pb push_back
#define si size()
#define E exp(1.0)
#define fixed cout.setf(ios::fixed)
#define fixeds(x) setprecision(x)
#define IOS ios::sync_with_stdio(false);cin.tie(0)
 using namespace std;
 ll gcd(ll a,ll b){if(a<0)a=-a;if(b<0)b=-b;return b==0?a:gcd(b,a%b);}
template<typename T>void read(T &res){bool flag=false;char ch;while(!isdigit(ch=getchar()))(ch=='-')&&(flag=true);
for(res=ch-48;isdigit(ch=getchar());res=(res<<1)+(res<<3)+ch - 48);flag&&(res=-res);}
ll lcm(ll a,ll b){return a*b/gcd(a,b);}
ll qp(ll a,ll b,ll mod){ll ans=1;if(b==0){return ans%mod;}while(b){if(b%2==1){b--;ans=ans*a%mod;}a=a*a%mod;b=b/2;}return ans%mod;}//快速幂%
ll qpn(ll a,ll b, ll p){ll ans = 1;a%=p;while(b){if(b&1){ans = (ans*a)%p;--b;}a =(a*a)%p;b >>= 1;}return ans%p;}//逆元   (分子*qp(分母,mod-2,mod))%mod;
ll a[222222];
ll k;
ll n;
bool check(ll x){
ll last=0;
ll now=0;
for(int i=1;i<=n;i++){
  last=(last+min(a[i],x)); //剩下的
  if(last>=x){last%=x;now++;}
   if(now>=k)return true;
}
return false;
}
signed main(){

read(n);
read(k);
for(int i=1;i<=n;i++){
   read(a[i]);
}

sort(a+1,a+1+n);
ll l=0,r=1e18;
ll ma=0;
while(l<r){
  ll mid=l+(r-l)/2;
  if(check(mid)){
    l=mid+1;
    ma=max(ma,mid);
  }
  else{
  r=mid-1;
  }
}
ll rnm=-1;
ll cnm=-1;
ll fuck=-1;
if(check(l))rnm=l;
if(check(r))cnm=r;
if(check((l+r)/2))fuck=(l+r)/2;
//printf("%lld %lld %lld\n",ma,l,r);
printf("%lld\n",max(ma,max(rnm,max(cnm,fuck))));

}

你可能感兴趣的:(c++)