SDNUOJ 1539 恰当选择DP对象
Description
T组输入样例
N个物品,W最大承重
每个物品都有对应的w[i], v[i]
求总重不超W时最大价值V
01背包选择价值作为DP对象,详见小白书Page61
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
int dp[505][5005];
int w[505], v[505];
int N, W;
int main()
{
int t;
cin >> t;
while(t--)
{
scanf("%d%d", &N, &W);
for(int i = 1; i <= N; ++i)
scanf("%d%d", &w[i], &v[i]);
memset(dp, INF, sizeof(dp));
dp[0][0] = 0;
for(int i = 1; i <= N; ++i)
for(int j = 0; j <= 5000; ++j)
{
if(j < v[i])
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - v[i]] + w[i]);
}
int ans = 0;
for(int i = 0; i <= 5000; ++i)
{
if(dp[N][i] <= W)
ans = i;
}
cout << ans << '\n';
}
return 0;
}