题目

https://www.luogu.org/problemnew/show/P3052

思路

状压DP

用i表示状态:奶牛是否进车厢

设f[i]为状态为i,用最少的车箱数
设g[i]为车厢最后一节与省的容积

代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,w;
int a[20],f[1<<18],g[1<<18];
int main()
{
    scanf("%d%d",&n,&w);
    for(int i=1; i<=n; i++) scanf("%d",&a[i]);
    memset(f,63,sizeof(f));
    f[0]=1;
    g[0]=w;
    for(int i=0; i<(1<<n); i++) 
    {
        for(int j=1; j<=n; j++)
        {
            if(i&(1<<(j-1))) continue;
            if(g[i]>=a[j] && f[i|(1<<(j-1))]>=f[i])
            {
                f[i|(1<<(j-1))]=f[i];
                g[i|(1<<(j-1))]=max(g[i|(1<<(j-1))],g[i]-a[j]);
            }
            else if(g[i]<a[j] && f[i|(1<<(j-1))]>=f[i]+1)
            {
                f[i|(1<<(j-1))]=f[i]+1;
                g[i|(1<<(j-1))]=max(g[i|(1<<(j-1))],w-a[j]);
            }
        }
    }
    printf("%d",f[(1<<n)-1]);
    return 0;
}