PAT 1070. Mooncake (贪心)

给出n堆月饼的重量和总价 -- 可求每吨的均价

给出总共的购买量d, 求可获得的最大利润


很简单的。求均价后排降序,从均价最高的开始购入。


1. 基础知识不牢固,scanf double时是用 %lf 标识

2. 对struct排序时,并不调用struct的成员函数< -- 所以重载小于号是没用的,得用友元或者直接在结构声明之外定义函数。


#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

struct Mooncake
{
	double m_avg;
	double m_tot;
	Mooncake(double tot): m_tot(tot) {}
//  这么做是不对的
//	bool operator< (Mooncake a)
//	{
//		return m_avg > a.m_avg;
//	}
};

bool avg_cmp(const Mooncake& a, const Mooncake& b)
{
	return a.m_avg > b.m_avg;
}

vector<Mooncake> mooncake;
int n;
double d, tot, price, profit = 0;

int main()
{
	scanf("%d%lf", &n, &d);
	for (int i = 0; i < n; ++ i)
	{
		scanf("%lf", &tot); // 是%lf
		mooncake.push_back( Mooncake(tot) );
	}
	for (int i = 0; i < n; ++ i)
	{
		scanf("%lf", &price);
		mooncake[i].m_avg = price / mooncake[i].m_tot;
	}
//	sort(mooncake.begin(), mooncake.end());
	sort(mooncake.begin(), mooncake.end(), avg_cmp);

	for (size_t i = 0; i < mooncake.size() && d > 0; ++ i)
	{
		if (d >= mooncake[i].m_tot)
		{
			d -= mooncake[i].m_tot;
			profit += mooncake[i].m_avg * mooncake[i].m_tot;
		} else
		{
			profit += mooncake[i].m_avg * d;
			d = 0;
		}
	}

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

	return 0;
}


你可能感兴趣的:(C++,scanf,sort,pat)