基础greedy algorithm,sort函数调用
/*
ID: alexyua2
PROG: milk
LANG: C++
*/
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;
ifstream fin("milk.in");
ofstream fout("milk.out");
//ifstream fin("in.txt");
//ofstream fout("out.txt");
struct Farmer
{
int price;
int amount;
};
bool mycmp(Farmer,Farmer);
int main()
{
//input
int N,M;
fin>>N >>M;
int i;
vector<Farmer>farmers;
Farmer temp;
for(i=0;i<M;i++)
{
fin>>temp.price >>temp.amount;
farmers.push_back(temp);
}
//sort farmers by the price
sort(farmers.begin(),farmers.end(),mycmp);
//greedy algorithm
int cost = 0;
for(i=0;i<M;i++)
{
if(N >= farmers[i].amount)
{
N -= farmers[i].amount;
cost += farmers[i].amount * farmers[i].price;
}
else
{
cost += N * farmers[i].price;
break;
}
}
fout<<cost <<endl;
//close files
fin.close();
fout.close();
return 0;
}
bool mycmp(Farmer a,Farmer b)
{
return a.price<b.price;
}