我最近正在解决背包问题。在此版本的背包中,状态被视为价值,而不是重量。
问题与普通背包相同:有n个项目,第i个项目的权重为wi,值为vi。背包的容量为W。找到背包中可以填充的项目的最大可能值。
约束:1 <= n <= 100 1 <= W <= 10 ^ 9 1 <= wi <= W 1 <= vi <= 1000
输入:n W
w1 v1 w2 v2 w3 v3 ..... wn vn
由于重量值大,我们必须在状态下取值,结果将是最小的重量。尽管我已经解释了问题,但是如果您需要更多详细信息,this is the problem link.
下面的代码是我尝试解决的问题。我使用了基于1的索引。我无法找出错误。我曾尝试调试代码,但没有帮助。我从2天开始就一直坚持下去。请帮忙。
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int n,W;
cin>>n>>W; // no. of elements and maxm. Weight
int v[n+1],w[n+1]; // array for value and weight
int dp[n+1][100001]; // dp array with size n+1 and 10^5+1 (for v max value 1000, and for n 100)
// Initializing arrays
v[0]=INT_MAX; w[0]=INT_MAX;
for (int i = 0; i < n+1; ++i)
{
for (int j = 0; j < 100001; ++j)
{
dp[i][j]=INT_MAX;
}
}
for (int i = 1; i < n+1; ++i){
cin>>w[i]>>v[i];
}
dp[1][0]=0; // for 0 value, no value for weight
dp[1][v[1]]=w[1];
for (int i = 2; i < n+1; ++i)
{
dp[i][0]=0;
for (int j = 1; j < 100001; ++j)
{
dp[i][j]=dp[i-1][j]; // excluding the element
if(j-v[i]>=1){
dp[i][j]=min(dp[i][j],w[i]+dp[i-1][j-v[i]]); // min of including and excluding element
}
}
}
// to find the max value for which weight is <=W
for(int i=100000; i>=1; i--){
if(dp[n][i]<=W){
cout<<i; break;
}
}
return 0;
}
答案 0 :(得分:1)
您的代码存在一些问题:
INT_MAX
dp[1][v[1]]=w[1];
无色线for (int j = 1; j < 100001; ++j)
j
为有效权重if(j-v[i]>=1){
与上面相同这是固定版本:
#include <iostream>
#include <limits.h>
#define ll long long
using namespace std;
int main()
{
int n,W;
cin>>n>>W; // no. of elements and maxm. Weight
ll v[n+1],w[n+1]; // array for value and weight
ll dp[n+1][100001]; // dp array with size n+1 and 10^5+1 (for v max value 1000, and for n 100)
// Initializing arrays
v[0]=1e17; w[0]=1e17;
for (int i = 0; i < n+1; ++i)
{
for (int j = 0; j < 100001; ++j)
{
dp[i][j]=INT_MAX;
}
}
for (int i = 1; i < n+1; ++i){
cin>>w[i]>>v[i];
}
dp[0][0]=0; // for 0 value, no value for weight
for (int i = 1; i < n+1; ++i)
{
dp[i][0]=0;
for (int j = 0; j < 100001; ++j)
{
dp[i][j]=dp[i-1][j]; // excluding the element
if(j-v[i]>=0){
dp[i][j]=min(dp[i][j],w[i]+dp[i-1][j-v[i]]); // min of including and excluding element
}
}
}
// to find the max value for which weight is <=W
for(int i=100000; i>=0; i--){
if(dp[n][i]<=W){
cout<<i; break;
}
}
return 0;
}