杭电1009题

#include<iostream>
#include <iomanip>
#include<vector>
#include<algorithm>
using namespace std;

class Room
{
public:
	int iJavaBean;
	int iCatFood;
	double douRate; 
	Room():iJavaBean(0),iCatFood(0)
	{
		douRate = 0;
	}
	Room(int x, int y):iJavaBean(x),iCatFood(y)
	{
		douRate = 1.0*iJavaBean / iCatFood;
	}
};

bool CompByRate(Room r1, Room r2)
{
	return r1.douRate > r2.douRate;

}

int main()
{
	int iFood;
	int iRoomNum;
	while(cin >> iFood >> iRoomNum)
	{
		if(-1 == iFood && -1 == iRoomNum)
		{
			return 0;
		}
		else
		{
			int iJavaBean, iCatFood;
			vector<Room> vecRoom(iRoomNum); 
			double douChangeJavaBean = 0; 
			for(int i = 0; i < iRoomNum; i++)
			{
				cin >> iJavaBean >> iCatFood;
				Room room(iJavaBean, iCatFood);
				vecRoom[i] = room;
			}//for_loop
			
		 sort(vecRoom.begin(), vecRoom.end(), CompByRate);                               
		 
		 for(int i = 0; i < iRoomNum; i++)
		 {
		 		if(iFood >= vecRoom[i].iCatFood)
		 		{
		 			douChangeJavaBean += vecRoom[i].iJavaBean;
		 			iFood = iFood - vecRoom[i].iCatFood;
		 		}
		 		else
		 		{
		 			douChangeJavaBean += 1.0 * iFood * vecRoom[i].iJavaBean / vecRoom[i].iCatFood;
		 			iFood = 0;
		 			break;
		 		}
		 }
			
		 cout << fixed <<setprecision(3) << douChangeJavaBean << endl;
			
		}//if_loop
		
	}//while_loop
	
	return 0;
}

题目:点击打开链接


贪心算法

attention:1> 比较函数的返回。

                    2> 小数点后几位的输出。点击打开链接 


你可能感兴趣的:(杭电1009题)