CF1066D Boxes Packing

2018-10-22 18:37:30


来一发通俗易懂的二分题解

直接二分答案

要放 $k$ 个物品就要删掉 $n-k$ 个物品

所以对于一个答案 $k$ ,要放的是 $[n-k+1,n]$ 这 $k$ 个物品

一个一个放,当前盒子能放开就放,放不开就新开一个

感觉代码还是比较简短的

#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
#define reg register
using namespace std;
const int N=2e5+5;
int n,m,V,a[N];
inline int read()
{
    int x=0,w=1;
    char c=getchar();
    while (!isdigit(c)&&c!='-') c=getchar();
    if (c=='-') c=getchar(),w=-1;
    while (isdigit(c))
    {
        x=(x<<1)+(x<<3)+c-'0';
        c=getchar();
    }
    return x*w;
}
inline bool check(int k)
{
    int res=V,now=1;
    for (int i=n-k+1;i<=n;i++)
    {
        if (res>=a[i]) res-=a[i];
        else ++now,res=V-a[i];
    }
    return now<=m;
}
int main()
{
    n=read(),m=read(),V=read();
    for (reg int i=1;i<=n;a[i++]=read());
    int l=0,r=n,ans=0;
    while (l<=r)
    {
        int mid=(l+r)>>1;
        if (check(mid)) ans=mid,l=mid+1;
        else r=mid-1;
    }
    printf("%d\n",ans);
    return 0;
}