基础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;
}
本文介绍了一个基于C++实现的基础贪心算法案例,通过排序和贪心策略解决奶农售奶的问题。代码中详细展示了如何定义结构体、比较函数以及主流程逻辑。
381

被折叠的 条评论
为什么被折叠?



