.
0/1 knapsack problem : Given a knapsack of capacity V, now there are multiple items to be put into the knapsack, each item has a certain volume and value, and the total value of the items that can be put in the knapsack is the largest ( The packing problem given below is actually the same, seeking the minimum total space can actually be understood as seeking to maximize the volume of the loaded items, then assign the value of the item to the volume, and seeking the maximum volume is also seeking the maximum value!)!
( Partial Knapsack Problem): Greedy
For the partial knapsack problem, because the item can be put in part instead of having to be put in the whole. Therefore, the greedy algorithm can be used directly to solve it directly. What is a greedy algorithm? In layman's terms, every step of the choice is optimal.
( All Knapsack Problems): Dynamic Programming
Example for all knapsack problems: Algorithm training boxing problemClick to open the link
There is a box with a capacity of V (positive integer, 0 <= V <= 20000), and n items (0 < n <= 30), each of which has a volume (positive integer).
It is required to take any number of n items and put them into the box to minimize the remaining space of the box.
the second line is an integer, indicating that there are n items;
the next n lines, each line has an integer indicating the respective volumes of the n items.
Sample input
24
6
8
3
12
7
9
7
//All knapsack problems #include<iostream> #include<cmath> #include<string> #include<cstring> #include<algorithm> #include<iomanip> using namespace std; int Volume[30]; int Need[30];//Array of capacity and demand (value) int cache[40000][30];//Just writing 20000 will make an error int Package(int capacity,int item) {//capacity容量 if (item==-1) {//Boundary conditions return 0;//return 0 } int &ret = cache[capacity][item];//Dynamic programming fixed writing if (ret! = 0) { return ret; } // don't put in ret=Package(capacity, item - 1); //Put in (forgot to consider the condition of capacity) if (capacity>=Volume[item]) { ret = max(ret, Package(capacity - Volume[item], item - 1) + Need[item]); } return ret; } int main() { int ca,n;//箱子容量和物品数目 cin >> ca>>n; for (int i = 0; i < n;i++) { cin >> Volume[i]; Need[i] = Volume[i]; } cout << ca-Package(ca,n-1) << endl; return 0; }
.
选法应该是2^n次方(即每个物品都是选或者不选的区别)