背包问题2
Time Limit:1000MS Memory Limit:65536K
Description
一个背包容积为T(0<=T<=2000),现在有N(0<N<=1000)种物品,每种物品有一定体积V(1<=V<=5000)。每种物品有无限多个。从这N种物品中选取若干个装入背包内,使背包所剩的空间最小。请求出最小的剩余空间?
Input
第一行,空格间隔的两个整数T和N,分别表示背包的容积和物品的种数。
第二行,用空格间隔的N个整数,表示每种物品的体积。
Output
只有一行,一个整数,表示最小剩余的背包空间。
Sample Input
30 4
14 7 13 11
Sample Output
1
#include <stdio.h>
inline void _r(int& d)
{
char t=getchar();bool f=false;
while(t<'0'||t>'9') {if(t=='-') f=true; t=getchar();}
for(d=0;t<='9'&&t>='0';t=getchar()) d=d*10+t-'0';
if(f) d=-d;
}
inline void _o(int d)
{
int o[30],top=1;
if(d==0){putchar('0');return ;}
if(d<0) {putchar('-');d=-d;}
while(d)
{
o[top++]=d%10;
d/=10;
}
for(--top;top;--top) putchar('0'+o[top]);
}
bool f[2001];
int main()
{
int i,j,n,t,a;
for(_r(t),_r(n),f[0]=1,i=1;i<=n;i++)
for(_r(a),j=a; j<=t;j++)
if(f[j-a])f[j]=1;
for(i=t;!f[i];i--);
_o(t-i);
return 0;
}