USACO Section 1.3 Mixing Milk

/*
ID: lucien23
PROG: milk
LANG: C++
*/

#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;

typedef struct Farmer
{
	int price;
	int amount;

	Farmer(){}

	Farmer(int p,int a)
	{
		price=p;
		amount=a;
	}
}Farmer;

bool comparer(Farmer farmer1,Farmer farmer2)
{
	//此处不能用<=,因为STL要求两元素相等时必须返回false
	return farmer1.price<farmer2.price;
}

int main()
{
	ifstream infile("milk.in");
	ofstream outfile("milk.out");
	if(!infile || !outfile)
	{
		cout<<"file operation failure!"<<endl;
		return -1;
	}

	int N,M;
	infile>>N>>M;
	Farmer *farmers=new Farmer[M];
	for (int i=0;i<M;i++)
	{
		int price,amount;
		infile>>price>>amount;
		farmers[i]=Farmer(price,amount);
	}

	sort(farmers,farmers+M,comparer);

	int totalMoney=0,remainAmount=N;
	for (int i=0;i<M && remainAmount>0;i++)
	{
		if(farmers[i].amount>=remainAmount)
		{
			totalMoney+=remainAmount*farmers[i].price;
			remainAmount=0;
		}else{
			totalMoney+=farmers[i].amount*farmers[i].price;
			remainAmount-=farmers[i].amount;
		}
	}
	outfile<<totalMoney<<endl;

	delete[] farmers;

	return 0;
}

你可能感兴趣的:(Algorithm,C++,USACO)