Description
你有n个物品和m个包。物品有重量,且不可被分割;包也有各自的容量。要把所有物品装入包中,至少需要几个包?
Input
第一行两个整数n,m(1<=n<=24,1<=m<=100),表示物品和包的数量。
第二行有n个整数a[1],a[2],…,a[n](1<=a[i]<=10^8),分别表示物品的重量。
第三行有m个整数c[1],c[2],…,c[m](1<=c[i]<=10^8),分别表示包的容量。
Output
如果能够装下,输出一个整数表示最少使用包的数目。若不能全部装下,则输出NIE。
Sample Input
4 3
4 2 10 3
11 18 9
Sample Output
2
HINT
Source
思维难度:省选
代码难度:NOIP+
#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
#define lowbit(x) (x&(-x))
using namespace std;
const int Maxn=1<<24;
const int inf=105;
int n,m,a[Maxn],c[inf],lim,f[Maxn],g[Maxn];
inline int read(){
int x=0,f=1;char c=getchar();
while(c<'0'||c>'9'){
if(c=='-')f=-1;
c=getchar();
}
while(c<='9'&&c>='0'){
x=x*10+c-'0';
c=getchar();
}
return x*f;
}
bool cmp(int x,int y){
return x>y;
}
int main(){
n=read();m=read();lim=(1<<n);
for(int i=1;i<=n;i++)a[i]=read();
for(int i=1;i<=m;i++)c[i]=read();
sort(c+1,c+1+m,cmp);
for(int i=n;i>=1;i--)a[(1<<(i-1))]=a[i];
int tmp=0,x;
for(int i=1;i<lim;i++){
f[i]=m+1;g[i]=-1;
for(int j=i;j;j-=tmp){
tmp=lowbit(j);x=i-tmp;
if(a[tmp]<=g[x]&&(f[x]<f[i]||(f[x]==f[i]&&g[x]-a[tmp]>g[i])))f[i]=f[x],g[i]=g[x]-a[tmp];
else if((f[x]+1<f[i]||(f[x]+1==f[i]&&c[f[x]+1]>g[i]+a[tmp]))&&c[f[x]+1]>=a[tmp])f[i]=f[x]+1,g[i]=c[f[i]]-a[tmp];
}
}
if(f[lim-1]>m)puts("NIE");
else printf("%d\n",f[lim-1]);
return 0;
}