如何解决分数背包算法分段错误
我试图通过编写一个函数 get_optimal_value 来解决分数背包问题,该函数返回给定背包容量和物品重量和价值的总最优值。在函数get_optimal_value 中,我在v_per_w[i] = values[i]/weights[i];
上遇到了分段错误问题,我不确定发生了什么,因为我看不到访问外部内存的位置。
这是我的程序。感谢帮助:D
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
double get_optimal_value(int capacity,vector<int> weights,vector<int> values) {
double value = 0.0;
vector<double> v_per_w = {};
for (int i =0; i<weights.size(); ++i){
v_per_w[i] = values[i]/weights[i]; //calculate v/w for the vector
}
//as long as capacity is not full
while (capacity !=0){
auto it = std::max_element(v_per_w.begin(),v_per_w.end()); //find max element in v/w
auto it2 = find(v_per_w.begin(),v_per_w.end(),*it); // find the index of that max element in v/w
int largest_index = it2 - v_per_w.begin();
if (capacity>=weights[largest_index]){
value+= values[largest_index]; //if capacity is more than the weight of that max v/w,add it all in
}
else{
value += v_per_w[largest_index] * capacity; //else add whatever weight you can of that max v/w
}
values.erase(values.begin(),values.begin()+largest_index-1); //remove that item from all the vectors
weights.erase(weights.begin(),weights.begin()+largest_index-1);
v_per_w.erase(v_per_w.begin(),v_per_w.begin()+largest_index-1);
}
return value;
}
int main() {
int n;
int capacity;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cin >> values[i] >> weights[i];
}
double optimal_value = get_optimal_value(capacity,weights,values);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
解决方法
vector<double> v_per_w = {};
这会创建一个新的 vector
,它是完全空的。它没有任何价值。紧接着:
v_per_w[i] = values[i]/weights[i]; //calculate v/w for the vector
这会尝试更改 v_per_w
的现有值。然而,由于 v_per_w
是完全空的,所以它没有值;这几乎可以肯定地保证会产生您所观察到的崩溃类型。 v_per_w[something]
不会向向量添加新值。它修改/访问向量中的现有值,这些值必须已经存在。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。