Section 1.3 Mixing Milk

基础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语言
个人分类: Algorithm
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Section 1.3 Mixing Milk

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭