[英]This knapsack code is showing a float[float] invalid type error. what may be the reason for this?
This following piece of knapsack code is showing a float[float] error at line 32,33.下面这段背包代码在第 32,33 行显示了一个 float[float] 错误。 why is this happening?为什么会这样? I am not able to find out the reason why.我无法找出原因。 Any help would be greatful.任何帮助都会很棒。
//maximum value of loot
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int maxi(int a , int b)
{
if(a>b) return a;
else return b;
}
int main()
{
int n,W,V=0;
float v,w,j;
vector<int> values;
vector<int> weights;
vector<float> vbyw;
cin>>n>>W;
for(int i = 0 ; i<n; i++)
{
cin>>v>>w;
values.push_back(v);
weights.push_back(w);
vbyw.push_back(float(v/w));
}
sort(vbyw.begin(),vbyw.end());
j = vbyw.size()-1;
while(W>0 && j>0)
{
W = W - maxi(w[j],W);
V = V + maxi(w[j],W)*vbyw[j];
j--;
}
cout<<V;
return 0;
}
The problem is because in line 32, 33 you have subscript variable 'w' in place of 'weight' array.问题是因为在第 32、33 行,您有下标变量 'w' 代替了 'weight' 数组。 And one more thing if you are using 'j' for indexing than declare it 'int' not float.还有一件事,如果您使用 'j' 进行索引而不是将其声明为 'int' 不是浮动的。
I am not sure that your algo will work.我不确定你的算法会起作用。 But it will run now.但它现在会运行。 If you need help in algo than you can comment.如果您在算法方面需要帮助,则可以发表评论。
//maximum value of loot
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int maxi(int a , int b)
{
if(a>b) return a;
else return b;
}
int main()
{
int n,W,V=0,j;// line i have changed
float v,w;
vector<int> values;
vector<int> weights;
vector<float> vbyw;
cin>>n>>W;
for(int i = 0 ; i<n; i++)
{
cin>>v>>w;
values.push_back(v);
weights.push_back(w);
vbyw.push_back(float(v/w));
}
sort(vbyw.begin(),vbyw.end());
j = vbyw.size()-1;
while(W>0 && j>0)
{
W = W - maxi(weights[j],W); // line i have changed
V = V + maxi(weights[j],W)*vbyw[j]; // line i have changed
j--;
}
cout<<V;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.