01背包
#include <iostream>
using namespace std;
const int N = 110, M = 1010;
int n, m;
int f[M];
int v[N], w[N];int main()
{
cin >> m >> n;
for (int i = 1; i <= n; i ++ ) cin >> v[i] >> w[i];
for (int i = 1; i <= n; i ++ )
for (int j = m; j >= v[i]; j -- )
f[j] = max(f[j], f[j - v[i]] + w[i]);
cout << f[m] << endl;
return 0;
}
取硬币
#include <iostream>
using namespace std;
const int MOD = 1e9 + 7, N = 110, M = 1e5 + 10;
int n1, n2, m;
int f[M];
int v[N];int main()
{
cin >> n1 >> n2 >> m;
for (int i = 1; i <= n1; i ++ ) cin >> v[i];
for (int i = n1 + 1; i <= n1 + n2; i ++ ) cin >> v[i];
for (int i = 0; i <= n1 + n2; i ++ ) f[0] = 1;
for (int i = 1; i <= n1; i ++ )
for (int j = v[i]; j <= m; j ++ )
f[j] = (f[j] + f[j - v[i]]) % MOD;
for (int i = n1 + 1; i <= n1 + n2; i ++ )
for (int j = m; j >= v[i]; j -- )
f[j] = (f[j] + f[j -v[i]]) % MOD;
cout << f[m];
return 0;
}
完全背包
#include <iostream>
using namespace std;
const int N = 1e4 + 10, M = 1e7 + 10;
int n, m;
long long f[M];
int v[N], w[N];int main()
{
cin >> m >> n;
for (int i = 1; i <= n; i ++ ) cin >> v[i] >> w[i];
for (int i = 1; i <= n; i ++ )
for (int j = v[i]; j <= m; j ++ )
f[j] = f[j - v[i]] + w[i];
cout << f[m] << endl;
return 0;
}