首页 > 代码库 > USACO 1.3 Mixing Milk(贪心)

USACO 1.3 Mixing Milk(贪心)

USACO Mixing Milk

简单的贪心,读入数据,按单价从小到大排序,然后从最便宜的买起,直到买够为止。

/*
  ID:twd30651
  PROG:milk
  LANG:C++
*/
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int N;
int M;
typedef struct node
{
    int P;
    int A;
}node;
node data[5001];
int cmp(const void *a,const void *b)//注意这里的cmp函数,要完全符合int(*)(const void *,const void *)的形式
{
    node an=*(node*)a;
    node bn=*(node*)b;
    return an.P>bn.P;//从小到大
}
int main(int argc,char *argv[])
{
    freopen("milk.in","r",stdin);
    freopen("milk.out","w",stdout);
    scanf("%d %d",&N,&M);
    int i=0;
    while(scanf("%d %d",&data[i].P,&data[i].A)==2)
        i++;
    qsort(data,i, sizeof(node),cmp);//快速排序
    int sum=0;
    int count=0;
    for(int j=0;j<M;++j)
    {
        if(N-count>=data[j].A)
        {
            count+=data[j].A;
            sum+=data[j].A*data[j].P;
        }
        else
        {
            sum+=data[j].P*(N-count);
            break;
        }
    }
    printf("%d\n",sum);
    return 0;
}
Date: 2014-11-25T19:34+0800
Author: kirchhoff
Org version 7.9.3f withEmacs version 24
Validate XHTML 1.0


USACO 1.3 Mixing Milk(贪心)