[DP] [模板] 01背包
1.标准模板
以横轴坐标为体积
以纵轴坐标为当前物品至首物品
则 dp[i][j] 即为 OPT(体积j, 物品1 - i)
//#pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
const int MAXN = 1e6 + 10;
struct good
{
int val, size;
}arr[MAXN];
int sval, len;
int dp[110][11000] = {0};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>sval>>len;
for(int i = 1; i <= len; i++)
{
cin>>arr[i].size>>arr[i].val;
}
for(int i = 1; i <= len; i++)
{
for(int j = 1; j <= sval; j++)
{
if(j < arr[i].size)
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - arr[i].size] + arr[i].val);
}
}
cout<<dp[len][sval]<<endl;
return 0;
}
2.空间压缩
#include<iostream>
using namespace std;
int dp[11000]={0}, volume[1000], value[1000];
int main()
{
int len, sumvolume;
cin>>len>>sumvolume;
for(int i = 1; i <= len; i++)
cin>>volume[i]>>value[i];
for(int i = 1; i <= len; i++)
{
for(int j = sumvolume; j >= volume[i]; j--)
{
dp[j] = max(dp[j], dp[j - volume[i]] + value[i]);
}
}
cout<<dp[sumvolume]<<endl;
return 0;
}
[Dynamic programming]动态规划