knapsack problem I |
difficulty level: B; run time limit: 1000ms; run space limit: 51200KB; code length limit: 2000000B |
Questions Description |
has a backpack volume of v and n items, and gives each item a volume. Request from n items, any number of packs into the backpack, so that the remaining space of the backpack is minimal. |
input |
first row two positive integers V and n, respectively, indicating the volume of the backpack and the number of items to be loaded; the second line includes n A positive integer that represents the volume of n items, separated by a space between 22. |
output |
A number that indicates the minimum amount of space remaining in the backpack |
input Example |
24 6 8 3 12 7 9 7 |
output Show Example |
0 |
Other instructions |
data range : 0<v≤20000,0<n≤30 |
|
It's too simple, transfer equation: Dp[j]=max (dp[j],dp[j-a[i]]+a[i]);.
1#include <iostream>2#include <cstring>3 using namespacestd; 4 intMain ()5 { 6 intV,n;7Cin>>v>>N; 8 inta[n],dp[v+1]; 9Memset (DP,0,sizeof(DP)); Ten for(intI=0; i<n;i++) One { ACin>>A[i]; - for(intj=v;j>=a[i];j--) -Dp[j]=max (dp[j],dp[j-a[i]]+A[i]); the } -cout<<v-Dp[v]; -}
View Code
Classic Backpack problem