64,679
社区成员
发帖
与我相关
我的任务
分享
#include <fstream>
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int Knapsack(int value[], int weight[], int n, int w);
int main()
{
int B, size, *value, *weight;
int mostValue = 0;
ifstream inFile("Knapsack.txt");
if( inFile.is_open() ) {
cout << "Open file success!\n";
inFile >> B;
inFile >> size;
value = new int[size];
weight = new int[size];
for( int i = 0; i < size; ++i ) {
inFile >> value[i];
inFile >> weight[i];
}
} else {
cerr << "Open file failure.\n";
return 0;
}
inFile.close();
cout << "Here's the most value: ";
mostValue = Knapsack(value, weight, size, B);
cout << "Most Value = " << mostValue << endl;
return 0;
}
int Knapsack(int value[], int weight[], int n, int w) {
int v[n][w];
for( int i = 0; i < n; ++i)
v[i][0] = 0;
for( int j = 0; j < w; ++j)
v[0][j] = 0;
for( int i = 1; i <= n; ++i ) {
for( int j = 1; j <= w; ++j ) {
v[i][j] = v[i - 1][j];
if( weight[i] <= j )
v[i][j] = max( v[i][j], v[i - 1][j - weight[i]] + value[i] );
}
}
return v[n][w];
}