杭电OJ hdu1009 FatMouse' Trade

仅作为水题学习记录,转载随意,欢迎大神们拍砖

oj地址http://acm.hdu.edu.cn/showproblem.php?pid=1009

Problem Description
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
Input
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1's. All integers are not greater than 1000.
 

Output
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.
 

Sample Input

5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
 

Sample Output

13.333 31.500

思路:

先算出每个房间中JavaBean和Cat Food的比重,优先选取比重大的。 如第一个测试数据,7/2=3.5,4/3=1.3333,5/2=2.5,先取7和5,最后再按比例在4中取,因此结果为7+5+4*(1/3)=13.333

C++ 代码

/*
注意精度问题,weight要用double,用float会WA。
*/
#include 
#include 
#include 
#include 


using namespace std;


struct Unit
{
	int javaBean;
	int catFood;
	double weight;//精度问题,float产生WA
};


bool compareByWeight(Unit unit1, Unit unit2)
{
	return (unit1.weight > unit2.weight);
}


int main()
{
#ifdef ONLINE_JUDGE
#else
	streambuf* backup;
	ifstream fin;
	fin.open("../../../data/hdu1009.txt", ios_base::in);
	backup = cin.rdbuf();
	cin.rdbuf(fin.rdbuf());
#endif


	int M, N;
	double result;//JavaBean
	int catFood;//cat Food
	vector data;
	while (cin >> M >> N)
	{
		data.clear();
		catFood = M;
		if (M == -1 && N == -1)
			break;
		for (int i = 0; i < N; ++i)
		{
			Unit unit;
			cin >> unit.javaBean >> unit.catFood;
			unit.weight = unit.javaBean / (double)unit.catFood;
			data.push_back(unit);
		}


		sort(data.begin(), data.end(), compareByWeight);


		result = 0.0;
		for (vector::iterator itr = data.begin(); itr != data.end(); ++itr)
		{
			int currCatFood = (*itr).catFood;
			int bean = (*itr).javaBean;
			if (catFood >= currCatFood)
			{
				catFood -= currCatFood;
				result += bean;
			}
			else if (catFood >= 0 && catFood < currCatFood)
			{
				result = result + (catFood / (double)currCatFood) * bean;
				break;
			}
			else
			{
				break;
			}
		}


		cout.setf(ios::showpoint);
		cout.precision(6);
		cout.setf(ios::fixed);
		cout << result << endl;
	}


#ifdef ONLINE_JUDGE
#else
	fin.close();
	cin.rdbuf(backup);
	system("pause");
#endif
	return 0;
}

ps:吐槽下,题目简单,但是作为一个OJ新水货,开始weight用的float类型,一直Wrong Answer,搞得我怀疑方法不对,换成double才AC掉,瞬间一万匹草泥马在心中崩腾而过。。。





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