1,01背包问题
#include<iostream>
using namespace std;
const int i = 1000;
int w[i], v[i];
int f[i][i];
int main()
{
int N, V;//N件物品,背包容量V
cin >> N >> V;
for (int i = 1; i <= N; i++)
{//输入数据
cin >> v[i]>>w[i];
}
//求出每个组合的最优解
for (int i=1;i<=N;i++)
{
for (int j = 1; j <= V; j++)
{
if (j < v[i])//不够装
{
f[i][j] = f[i - 1][j];
}
else
//f[i-1][j]表示的是不选
f[i][j] = max(f[i - 1][j], f[i - 1][j - v[i]] + w[i]);
}
}
cout << f[N][V] << endl;
system("pause");
return 0;
}
2, 完全背包问题
#include<iostream>
using namespace std;
const int Max = 1001;
int f[Max];
int v[Max],w[Max];
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{//输入物品信息
cin >> v[i] >> w[i];
}
//求出每个组合的最优解
for (int i = 1; i <= n;i++)
{
for (int j = 1; j <= m; j++)
{
if (j < v[i])
{
f[j]=f[j];
}
else
{
f[j] = max(f[j],f[j - v[i]] + w[i]);
}
}
}
cout << f[m] << endl;
return 0;
}
3,多重背包问题
#include<iostream>
#include <algorithm>
using namespace std;
const int Max = 1005;
int f[Max][Max], v[Max], w[Max], s[Max];
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{//赋值
cin >> v[i] >> w[i] >> s[i];
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <=m; j++)
{
for (int k = 0; k <=s[i] ; k++)
{
if (j >= k*v[i])
{
f[i][j] = max(f[i][j],f[i - 1][j - k * v[i]] + k * w[i]);
}
else
{
f[i][j] = f[i-1][j];
}
}
}
}
cout << f[n][m] << endl;
system("pause");
return 0;
}