二维数组
#include <iostream>
#include <string>
#include <math.h>
#include<algorithm>
#include<cstdio>
#include<string.h>
using namespace std;
int n, c;
int m[1000], v[1000];
int f[1000][1000];
int main()
{
cin >> c >> n;
for (int i = 1; i <= n; i++)
{
cin >> m[i] >> v[i];
f[i][0] = 1;
}
f[0][0] = 1;
for (int i = 1; i <= n; i++)
for (int j = 1; j <=c; j++) {
f[i][j] = f[i - 1][j];
if (j - m[i] >= 0)
f[i][j] = max(f[i - 1][j], f[i - 1][j - m[i]] + v[i]);
}
cout << f[n][c] << endl;
}
空间优化 一维数组
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<cmath>//把我所记住的头文件全写上了(大家不要学我);
using namespace std;
int n, c;//定义物品数量及背包容量;
int w[1000], v[1000];//定义数组w[i]和v[i]分别表示物品i的质量和价值(1000毫无意义);
int f[1000];//定义数组f[i][j]存放第i个时的当前最大值(乱说胡话);
int main()
{
cin >> c >> n;//输入n,c;
for (int i = 1; i <= n; i++)
cin >> w[i] >> v[i];//输入第1~n个物体的质量和价值 ;
for (int i = 1; i <= n; i++)
for (int j = c; j >= w[i]; j--)
f[j] = max(f[j], f[j - w[i]] + v[i]);
cout << f[c] << endl;//希望没输错……
}