[USACO12MAR]摩天大楼里的奶牛Cows in a Skyscraper
[USACO12MAR]摩天大楼里的奶牛Cows in a Skyscraper
题目描述
给出n个物品,体积为w[i],现把其分成若干组,要求每组总体积<=W,问最小分组。(n<=18)
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,w,a[20],f[300010],g[300010];
int read()
{
int n=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){n=n*10+c-'0';c=getchar();}
return n*f;
}
int main()
{
n=read(),w=read();
for(int i=1;i<=n;++i)a[i]=read();
memset(f,0x3f,sizeof(f));
g[0]=w;
f[0]=1;
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]-a[j],g[i|(1<<(j-1))]);
}
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(w-a[j],g[i|(1<<(j-1))]);
}
}
printf("%d",f[(1<<n)-1]);
return 0;
}