I am fairly new to C++. I have implemented the fractional knapsack problem in c++ for the course "Algorithmic Toolbox" on Coursera:
#include <iostream>
#include <iomanip>
using namespace std;
int get_max_index(double A[], double B[],int l)
{
/*
int A = array of value
int B = array of weights
int l = length of the array
*/
int p,Max{0};
for(int j=0;j<l;j++)
{
if((A[j]/B[j]) > Max){Max = A[j]/B[j];p = j;}
}
return p;
}
int main()
{
int n,W,q,Max{0},W1{0};
cin >> n >> W;
double values[n],weights[n],loot{0};
for(int i=0;i<n;i++)
{
cin >> values[i] >> weights[i];
}
for(int j=0;j<n;j++)
{
if(W==0){break;}
else
{
q = get_max_index(values,weights,n);
if(weights[q] <= W){W1 = weights[q];}
else{W1 = W;}
loot += W1 * (values[q]/weights[q]);
W -= W1;
weights[q] -= W1;
if(weights[q] == 0){values[q] = 0;}
}
}
cout << setprecision(4) << fixed;
cout << loot << endl;
}
After submitting this code I got a stack overflow error (unknown signal 11). Please help me understand why this happens and solution to this problem.
EDIT :
I have changed the code. I am not using the get_max_index function with dynamically sized arrays. Here is the new code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
long long int n,W,q,p,Max{0},W1{0};
cin >> n >> W;
long double values[n],weights[n],loot{0},VPU[n];
for(long long int i=0;i<n;i++)
{
cin >> values[i] >> weights[i];
VPU[i] = values[i] / weights[i];
}
for(long long int j=0;j<n;j++)
{
if(W==0){break;}
else
{
for(long long int k=0;k<n;k++)
{
if(VPU[k] > Max){Max = VPU[k];p=k;}
}
Max = 0;
q = p;
if(weights[q] <= W){W1 = weights[q];}
else{W1 = W;}
loot += W1 * (values[q]/weights[q]);
W -= W1;
weights[q] -= W1;
if(weights[q] == 0){VPU[q] = 0;}
}
}
cout << setprecision(4) << fixed;
cout << loot << endl;
}