簡單揹包問題(結合lambda)

#include "pch.h"
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;

typedef struct node {
	double weight;
	double value;
	double ave;
};

double v[1005] = { 0 };

int main()
{
    
	int N, T;
	cin >> N >> T;

	node* gold = new node[N + 1];
	double *ave = new double[N + 1];
	for (int i = 1; i <= N; i++)
	{
		cin >> gold[i].weight >> gold[i].value;
		gold[i].ave = gold[i].value / gold[i].weight;
	}

	sort(&gold[1], &gold[N + 1], [](node const &a, node const &b) {return a.ave > b.ave; });
	int j = 0;
	for (int i = 1; i <= N; i++)
	{
		while (gold[i].weight != 0)
		{
			if (T <= 0)	//容量爲零結束,不放入揹包
			{
				break;
			}
			++j;
			v[j] = v[j-1]+gold[i].ave;	//容量爲j最大價值
			--gold[i].weight;	//該價值的金幣堆總量減一
			--T;	//剩餘容量
		}
	}

	cout.setf(ios::fixed);
	cout.precision(2);
	cout << v[j] << endl;

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章