1070. Mooncake (25)

1.卡在测试点2比较久,结果发现amount也需要使用double才能通过,使用long long或者int都不行

2.贪心算法,每次取单位价格最高的mooncake

存储结构:

struct mooncakeNode{
	double amount;//需要使用double,才能通过测试点2
	double price;
	double unitPrice;
	mooncakeNode() :amount(0), price(0), unitPrice(0){};
};

AC代码:

//#include<string>
//#include<stack>
//#include<unordered_set>
//#include <sstream>
//#include "func.h"
//#include <list>
#include <iomanip>
#include<unordered_map>
#include<set>
#include<queue>
#include<map>
#include<vector>
#include <algorithm>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
#include<stack>
using namespace std;
/*
3 2000
180 150 100
7.5 7.2 4.5
3 20
180 150 100
7.5 7.2 4.5

0 20
 
3 0
180 150 100
7.5 7.2 4.5

3 1
180 150 100
7.5 7.2 4.5
*/
struct mooncakeNode{
	double amount;//需要使用double,才能通过测试点2
	double price;
	double unitPrice;
	mooncakeNode() :amount(0), price(0), unitPrice(0){};
};
bool cmp(const mooncakeNode&a, const mooncakeNode&b)
{
	if (a.amount == b.amount && a.price >= b.price) return true;
	else
	return (double)a.price*b.amount > (double)b.price*a.amount;
}
int main(void)
{
	
	int n, marketNeed;
	cin >> n >> marketNeed;
	vector<mooncakeNode> mooncake(n);
	for (int i = 0; i < n; i++)
	{
		cin >> mooncake[i].amount;
	}
	for (int i = 0; i < n; i++)
	{//输入总价格和求出单位价格
		cin >> mooncake[i].price;
		if (mooncake[i].amount == 0)
		{
			mooncake[i].price = 0;
			mooncake[i].unitPrice = 0;
		}
		else
			mooncake[i].unitPrice = mooncake[i].price / mooncake[i].amount;
	}
	sort(mooncake.begin(), mooncake.end(), cmp);

	double profit=0;
	for (int i = 0; i < n && marketNeed!=0; i++)
	{
		if (mooncake[i].amount == marketNeed)
		{//如果刚好相等,则全部要了
			profit += mooncake[i].price;
			marketNeed -= mooncake[i].amount;
		}
		else if (mooncake[i].amount < marketNeed)
		{//如果数量小于市场需要,则全部要了
			profit += mooncake[i].price;
			marketNeed -= mooncake[i].amount;
		}
		else
		{//如果数量大于市场需要,则取市场需要部分即可
			profit += mooncake[i].price*marketNeed/mooncake[i].amount;
			marketNeed = 0;
		}
	}
	printf("%.2lf", profit);
	//cout << setprecision(2) << profit << endl;

	return 0;
}


posted @ 2015-11-25 11:17  siukwan  阅读(173)  评论(0)    收藏  举报