背包算法

#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");
}
完全背包
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值