Please have a look at the following code. I've tried using max_element function and find function to complete the task, but shows segmentation error, when compiled. I've checked it is not out of bound. Kindly help me out, Also, if possible kindly suggest me some resource on C++ I know badics, I'm having difficulty in the STL part.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
double bag( int w, vector<int> values,vector<int> weights){
int index, ma;
double W1=0.0;
double V=0.0;
while(W1<=w)
{
ma=*max_element(values.begin(), values.end()) ;
auto it = find(values.begin(), values.end(), ma);
index = distance(values.begin(),it);
if(w-W1>=weights[index])
{
V=V+values[index];
W1=W1+weights[index];
}
else
{
V=V+values[index]*(w-W1)/weights[index];
}
values.erase(it);
weights.erase(it);
}
return V;
}
int main() {
int n;
int w;
double ans;
std::cin >> n >> w;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cin >> values[i] >> weights[i];
}
cout<<values[n-1];
ans = bag(w,values,weights);
cout<<ans;
}
Aucun commentaire:
Enregistrer un commentaire