- 01背包问题
先上版子。
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int f[maxn][maxn];
int v[maxn],w[maxn];
int main()
{int 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=0;j<=V;j++){if (j>=v[i]) f[i][j] = max(f[i-1][j],f[i-1][j-v[i]]+w[i]);else f[i][j] = f[i-1][j];}}int Max = 0;for (int i=1;i<=V;i++){Max = max(Max,f[n][i]);}cout<<Max;return 0;
}
板子不懂得推荐看:大佬详细讲解
再来优化:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1010;
int f[maxn];
int v[maxn], w[maxn];
int main()
{int 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 = V; j>=v[i]; j--){f[j] = max(f[j], f[j - v[i]] + w[i]);}}cout << f[V];return 0;
}