01背包
#include <iostream>
#include <algorithm>
using namespace std;
#define N 1010
int dp[N];
int main()
{
int n,m;
cin >> n >> m;
for(int i = 1; i<=n; i++)
{
int v,w;
cin >> v >> w;
for(int j = m; j>=v ; j--)
dp[j]=max(dp[j],dp[j-v]+w);
}
cout << dp[m];
return 0;
}
完全背包
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int dp[1010] ={0};
int n,m;
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
int v, w;
cin >> v >> w;
for(int j = v; j <= m; j++)
{
dp[j] = max(dp[j] , dp[j-v] + w);
}
}
cout << dp[m] << endl;
return 0;
}
多重背包
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int dp[110] = {0};
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; ++i)
{
int v,w,s;
cin >> v >> w >> s;
for(int i = 1; i <= s; i++)
for(int j = m; j >= v*i; j--)
dp[j] = max(dp[j] , dp[j-v] + w);
}
cout << dp[m] << endl;
return 0;
}
// 二进制优化
#include<iostream>
#include<algorithm>
#define N 2010
using namespace std;
int main()
{
int n,v;
cin >> n >> v;
int dp[N] = {0};
for(int i = 0; i < n; i++)
{
int x,y,z;
cin >> x >> y >> z;
int s[N] = {0};
int cnt = 0, tmp = z;
for(int j = 1; j <= tmp; j *= 2)
{
if(z > j)
{
z -= j;
s[cnt++] = j;
}
else
break;
}
if(z) s[cnt++] = z;
for(int q = 0; q < cnt; q++)
{
if(s[q]* x > v) break;
for(int j = v; j >= s[q]*x; j--)
dp[j] = max(dp[j], dp[j - s[q]*x] + y*s[q]);
}
}
cout << dp[v];
return 0;
}
分组背包
#include <iostream>
#include <algorithm>
#define N 110
using namespace std;
int main()
{
int dp[N] = {0};
int n, v;
cin >> n >> v;
while(n--)
{
int s; cin >> s;
for(int i = 0; i < s; i++)
{
int x,y; cin >> x >> y;
for(int j = v; j >= x; j--)
dp[j] = max(dp[j], dp[j - x] + y);
}
}
cout << dp[v];
return 0;
}