#include<iostream>
#include<algorithm>
using namespace std;
int rate[1000];
int order[1000];
bool cmp(int i, int j){
return rate[i]>rate[j]? true : false;
}
double Solver(int W, int p[], int w[], int n){
int P = 0;
for(int i=0;i<n;i++){
rate[i] = p[i]/w[i];
order[i] = i;
}
sort(order, order+n, cmp);
for(int i=0;i<n ;i++){
//cout << order[i] << endl;
if(W > w[order[i]]){
P = P + p[order[i]];
W = W - w[order[i]];
}else{
P = P + p[order[i]] * ((double)W/w[order[i]]);
break;
}
}
return P;
}
int p[1000];
int w[1000];
int main(){
int n;
cout << "Please enter the number of object N" << endl;
cin >> n;
for(int i=0;i<n;i++){
cout << "Please enter the profit and weight of subject "<<i << endl;
cin >> p[i] >> w[i];
}
cout << "Please enter the maximun wighet" << endl;
int W;
cin >> W;
cout << "The maximum profit : ";
cout <<Solver(W, p, w, n )<< endl;
system("pause");
}
完全背包
背包算法
最新推荐文章于 2025-03-28 09:05:06 发布