PTA L2-003 月饼

这是一道贪心算法的题,题目也直接告诉了我们是贪心去做,需要注意的是测试点3,因为给出的月饼的重量不一定是整数,因此要用double

#include
#include
using namespace std;

struct mooncake {
	double price;
	double weight;
	double value;

	bool operator <(const mooncake &c)
	{
		return value > c.value;
	}
};
mooncake m[1010];

int main()
{
	int n;
	int weight;


	cin >> n >> weight;

	for (int i = 0; i < n; i++)
		cin >> m[i].weight;

	for (int i = 0; i < n; i++)
	{
		cin >> m[i].price;
		m[i].value = m[i].price / m[i].weight;
	}

	sort(m, m + n);

	double value = 0;
	int index = 0;

	for (int i = 0; i < n; i++)
	{
		if (weight >= m[i].weight)
		{
			weight -= m[i].weight;
			value += m[i].price;
		}
		else
		{
			value += (float)weight / m[i].weight*m[i].price;
			break;
		}

	}

	printf("%.2lf\n", value);

	system("pause");
	return 0;
}

你可能感兴趣的:(算法)