有N件物品和一个容量为V的背包。第i件物品的费用是c[i],价值是w[i]。求解将哪些物品装入背包可使价值总和最大。
#include <iostream> #include <algorithm> #include <cstring> #define MaxObjNum 100 #define MaxPackageVolume 100000 using namespace std; int ObjNum, PackageVolume; int ObjWeight[MaxObjNum], ObjVal[MaxObjNum]; int BackUp[MaxPackageVolume][MaxObjNum]; int DynamicProgramming(int RemainV, int pos) { int ReturnVal; if (BackUp[RemainV][pos] != -1) ReturnVal = BackUp[RemainV][pos]; else if (pos == 0) { if (RemainV >= ObjWeight[pos]) ReturnVal = ObjVal[pos]; else ReturnVal = 0; } else if (RemainV >= ObjWeight[pos]) ReturnVal = max(DynamicProgramming(RemainV - ObjWeight[pos], pos - 1) + ObjVal[pos], DynamicProgramming (RemainV, pos - 1)); else ReturnVal = DynamicProgramming(RemainV, pos - 1); BackUp[RemainV][pos] = ReturnVal; return ReturnVal; } int main() { memset(BackUp, -1, sizeof(BackUp)); cin >> PackageVolume >> ObjNum; for (int i = 0; i < ObjNum; ++i) { cin >> ObjWeight[i] >> ObjVal[i]; } cout << DynamicProgramming(PackageVolume, ObjNum - 1) << endl; return 0; }