46. 携带研究材料(第六期模拟笔试)
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
int bag(int N, vector<int> &weight, vector<int> &value)
{
int M = weight.size();
vector<int> dp(N+1);
for (int i=0; i<N+1; i++)
{
dp[i] = weight[0]<=i ? value[0] : 0;
}
for (int i=1; i<M; i++)
{
for (int j=N; j>0; j--)
{
if (j-weight[i]>=0)
dp[j] = max(dp[j], dp[j-weight[i]]+value[i]);
}
}
return dp[N];
}
int main()
{
int M;
int N;
for (int i=0; i<2; i++)
{
if (i==0) cin >> M;
if (i==1) cin >> N;
}
vector<int> weight(M);
for (int i=0; i<M; i++)
{
cin >> weight[i];
}
vector<int> value(M);
for (int i=0; i<M;i++)
{
cin >> value[i];
}
// cout << M << " " << N << endl;
// cout << weight[0] << " " << weight[5] << endl;
// cout << value[0] << " " << value[5] << endl;
cout << bag(N, weight, value) << endl;
}
class Solution {
public:
bool canPartition(vector<int>& nums)
{
int target = 0;
for (int i=0; i<nums.size(); i++)
{
target += nums[i];
}
if (target%2 != 0) return false;
vector<int> dp(target/2+1, 0);
for (int i=0; i<nums.size(); i++)
{
for (int j=target/2;j>0;j--)
{
if (i==0)
{
if (j>=nums[i]) dp[j] = nums[i];
}
else
{
if (j-nums[i]<0) dp[j] = dp[j];
else dp[j] = max(dp[j], dp[j-nums[i]]+nums[i]);
}
}
}
if (dp[target/2] != target/2) return false;
return true;
}
};