hoj1003 Mixing Milk (哈工大)

//贪心法,使用排序函数,每次都找最便宜的牛奶,然后判断够没够重量

#include <iostream>

#include <algorithm>

#define X 5010

using namespace std;



typedef struct milk        //定义牛奶结构体

{

    int p;

    int a;

}milk;



int cmp(milk a,milk b)        //对牛奶结构体排序

{

    return a.p<b.p;    

}



int main()

{

    int n,m;

    freopen("sum.in","r",stdin);

    freopen("sum.out","w",stdout);

    while(cin>>n>>m)

    {

        struct milk milk[X];

        int i;

        for(i=0;i<m;i++)

            cin>>milk[i].p>>milk[i].a;        //输入牛奶价格、重量

        sort(milk,milk+m,cmp);                //使用排序函数进行排序

        int sum = 0,amount = 0;

        for(i=0;i<m;i++)

        {

            if(amount+milk[i].a>=n)            //够了的话

            {

                int need = n-amount;

                sum = sum + need*milk[i].p;

                break;

            }

            else                            //牛奶还没够

            {

                sum =sum + milk[i].p*milk[i].a;

                amount+=milk[i].a;

            }

        }

        cout<<sum<<endl;

    }

    return 0;

}

你可能感兴趣的:(in)