-1

This following piece of knapsack code is showing a float[float] error at line 32,33. 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;
    }
RAJU C
  • 21
  • 1
  • 6
  • I changed the datatype of j from float to int. But now I am getting invalid type float[int] error, – RAJU C Feb 26 '19 at 05:22

1 Answers1

0

The problem is because in line 32, 33 you have subscript variable 'w' in place of 'weight' array. And one more thing if you are using 'j' for indexing than declare it 'int' not float.

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;
}