http://poj.org/problem?id=3628
01背包
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <algorithm> 5 #define maxn 21 6 #define ll long long 7 using namespace std; 8 9 ll h[maxn]; 10 int n; 11 ll b; 12 ll dp[1000004]; 13 ll max1(ll a,ll b) 14 { 15 return a>b?a:b; 16 } 17 18 int main() 19 { 20 while(scanf("%d%lld",&n,&b)!=EOF) 21 { 22 ll v=0; 23 for(int i=1; i<=n; i++) 24 { 25 scanf("%lld",&h[i]); 26 v+=h[i]; 27 } 28 for(int i=1; i<=n; i++) 29 { 30 for(ll j=v; j>=h[i]; j--) 31 { 32 dp[j]=max(dp[j-h[i]]+h[i],dp[j]); 33 } 34 } 35 for(ll j=1; j<=v; j++) 36 { 37 if(dp[j]>=b) 38 { 39 printf("%lld ",dp[j]-b); 40 break; 41 } 42 } 43 } 44 return 0; 45 }