实施分数背包

时间:2016-09-30 18:32:11

标签: c++ algorithm stl knapsack-problem

我试图通过首先按对象的值与对象的权重的比率对元素进行排序来实现分数背包。我正在使用对的向量,其中对的第一个元素是对象的值,对的第二个元素是权重。 compbyrat函数用于通过值与权重的比率来比较矢量元素。我在下面的代码中遇到运行时错误。任何人都可以帮我找到错误吗?

#include <iostream>
#include<algorithm>
#include<vector>
#include<utility>
using namespace std;
bool compbyrat(const pair<long long int,long long int> &a, const pair<long long int,long long int> &b)
{
    return ((double)a.first/(double)a.second)< ((double) b.first/(double) b.second) ;
}
int main() {
    long long int n, weight;
    vector<pair<long long int,long long int> > v;
    cin>>n>>weight;
    for(long long int i = 0; i < n; i++){
        cin>>v[i].first>>v[i].second;
    }

    sort(v.begin(), v.end(), compbyrat);
    long long int currentweight = 0, ans =0;
    for(long long int i =0; i < n && currentweight < weight; i++){
        if(currentweight + v[i].second <= weight){
            ans = ans + v[i].first;
        }
        else{
            ans = ans + (((double)v[i].first/(double)v[i].second) * (weight -currentweight));
        }
    }
    cout<<ans;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

我能够通过一些修改来解决它。代码如下,

#include <iostream>
#include<algorithm>
#include<vector>
#include<utility>
#include<iomanip>
using namespace std;
bool compbyrat(const pair<long long int,long long int> &a, const pair<long long int,long long int> &b)
{
    return ((double)((double)a.first/(double)a.second)> (double)((double) b.first/(double) b.second)) ;
}
int main() {
    long long int n, weight;
    cin>>n>>weight;

    vector<pair<long long int,long long int> > v(n+2);
    for(long long int i = 0; i < n; i++){
        cin>>v[i].first>>v[i].second;
    }

    sort(v.begin(), v.end(), compbyrat);
    //cout<<v[0].first;
    long long int currentweight = 0;
    double ans = 0.0000;
    for(long long int i =0; i < n && currentweight < weight; i++){
        if(currentweight + v[i].second <= weight){
            ans = ans + v[i].first;
            currentweight = currentweight + v[i].second;
            //cout<<v[i].first<<" "<<v[i].second<<endl;
        }
        else{
            ans = ans + ((double)((double)v[i].first/(double)v[i].second) * (weight -currentweight));
            currentweight = currentweight + v[i].second;
        }


    }
    cout<<fixed << setprecision(4)<<ans;
    return 0;
}