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
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;
struct FoodTrade
{
int catFood;
int javaBean;
double rate;
};
bool cmp(FoodTrade x, FoodTrade y)
{
return x.rate > y.rate;
}
class FatMouseTrade
{
public:
void initialize();
void readCase(const int& m, int& n);
void compute();
void output();
private:
int catFood;
vector<FoodTrade> foodTrade;
double amount;
};
void FatMouseTrade::initialize()
{
catFood = 0;
amount = 0;
foodTrade.clear();
}
void FatMouseTrade::readCase(const int& m, int& n)
{
catFood = m;
while(n--)
{
FoodTrade food;
cin >> food.javaBean >> food.catFood;
food.rate = static_cast<double>(food.javaBean) / food.catFood;
foodTrade.push_back(food);
}
}
void FatMouseTrade::compute()
{
sort(foodTrade.begin(), foodTrade.end(), cmp);
for(int i = 0; i < foodTrade.size() && catFood != 0; ++i)
{
if(catFood < foodTrade[i].catFood)
{
amount += foodTrade[i].rate * catFood;
catFood = 0;
}
else
{
catFood -= foodTrade[i].catFood;
amount += foodTrade[i].javaBean;
}
}
}
void FatMouseTrade::output()
{
cout << setprecision(3) << setiosflags(ios::showpoint) << setiosflags(ios::fixed) << amount << endl;
}
int main()
{
FatMouseTrade fatMouseTrade;
int m, n;
while(cin >> m >> n && m != -1 && n != -1)
{
fatMouseTrade.initialize();
fatMouseTrade.readCase(m, n);
fatMouseTrade.compute();
fatMouseTrade.output();
}
return 0;
}
贪心算法