When I was a beginner, I tried to solve the problem with greedy ideas, but I still couldn't think of it for more than an hour.
// The two parameters F [k] in Max, and f [k-weight [I] + value [I] indicate the maximum value when the backpack capacity is K. // F [k] Is this meaning, not to mention. // While F [k-weight [I] + value [I] also indicates the maximum value when the backpack capacity is K. Why? // First, F [k-weight [I] indicates the capacity of a backpack with K-weight [I, that is to say, F [k-weight [I] // indicates that the capacity is less than weiht [I] to the value of K, + walue [I] makes up for the difference. So ...... // If you pair f [k] = max (F [K], (F [k-weight [I] + value [I]); this sentence is not very clear, // The following code will help you. // cout <"I =" <I + 1 <"f [" <k <"] = "<F [k] <Endl;
#include <iostream>using namespace std;int f[12881];int main(){ int Num, TotalWeight, i, j, k, weight[12881], value[12881]; cin >> Num >> TotalWeight; for(i = 0; i < Num; ++i) cin >> weight[i] >> value[i]; for(i = 0; i < Num; ++i){ for(k = TotalWeight; k >= weight[i]; --k){ f[k] = max(f[k], (f[k - weight[i]] + value[i])); } } cout << f[TotalWeight] << endl; return 0;}