PAT甲级 1070 Mooncake (25 分)

\quad 将月饼按照每吨的价格从大到小排序,之后每次从价格高的开始取,若剩下的总重量大于当前月饼重量,则全部取,否则取当前剩余总重量对应当前月饼的价格并退出。程序如下:

#include 
using namespace std;

struct Cake
{
	float w, p, pp;
}cake[1010];

bool cmp(const Cake &c1, const Cake &c2)
{
	return c1.pp>c2.pp;
}

int main(int argc, char const *argv[])
{
	int n;
	float d;
	scanf("%d%f", &n, &d);
	float w[n], p[n];
	float temp;
	for (int i = 0; i < n; ++i)
	{
		scanf("%f", &temp);
		cake[i].w = temp;
	}
    for (int i = 0; i < n; ++i)
    {
    	scanf("%f", &temp);
    	cake[i].p = temp;
    	cake[i].pp = temp*1.0/cake[i].w;
    }
	sort(cake, cake+n, cmp);
	float res = 0.0;
	for (int i = 0; i < n; ++i)
	{
		if(d-cake[i].w>=0.0)
		{
			res += cake[i].p;
			d -= cake[i].w;
		}
		else 
		{
			res += d*cake[i].pp;
			break;
		}
	}

	printf("%.2f\n", res);
	return 0;
}

你可能感兴趣的:(PAT甲级)