01背包问题,用动态规划来解
在对第i个物品检索时随时更新如果有j的空余位置,能装下的最大价值为多少
#include <iostream>
//#include <stdio>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <map>
#include <cmath>
#include <string>
#include <queue>
#include <stack>
using namespace std;
const int N = 2000;
int max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
int best[N][N];
int value[N];
int need[N];
int n, v, w;
int main()
{
int i, j;
while (scanf("%d", &n) != EOF)
{
scanf("%d", &w);
for (i = 1; i <= n; i++)
{
scanf("%d%d", &need[i], &value[i]);
// cin >> value[N] >> need[N];
}
for (i = 0; i <= w; i++)
best[0][i] = 0; //下面是核心代码
for(i=1;i<=n;i++) //对每个物品进行一遍检索
for (j = 1; j <= w; j++) //假设有j的空余位置,可以有多大的最大价值
{
if (j < need[i])
best[i][j] = best[i - 1][j];
else
best[i][j] = max(best[i - 1][j - need[i]] + value[i], best[i - 1][j]);//状态转移方程
}
//for (i = 0; i <= n ; i++)
// for(j=0;j<=w;j++)
// cout <<"i= "<<i<<" ,j= "<<j<<" "<< best[i][j] << endl;
cout << best[n][w] << endl;
}
return 0;
}