Section 1.3 milk

标准的贪心,先将供应商按照价格的升序排序,然后按需购买价格低的牛奶就可以得到最小的总价。

/*
ID:yucept21
LANG:C++
TASK:milk
*/

#include<cstdio>
#include<cstdlib>
#include<cstring>

typedef struct tt
{
int price, amount;
}T;

int N, M;
T milk[5005];
int cmp( const void *_p, const void *_q)
{
T *p = (T *)_p;
T *q = (T *)_q;
return p->price - q->price;
}

int main()
{
freopen( "milk.in", "r", stdin);
freopen( "milk.out", "w", stdout);
scanf( "%d%d", &N, &M);
for( int i = 0; i < M; i++)
scanf( "%d%d", &milk[i].price, &milk[i].amount);
qsort( milk, M, sizeof( milk[0]), cmp);
int ans = 0;
for( int i = 0; i < M; i ++)
{
if( N >= milk[i].amount) {
ans += milk[i].price * milk[i].amount;
N -= milk[i].amount;
}

if( N < milk[i].amount) {
ans += N * milk[i].price;
break;
}
}
printf( "%d\n", ans);
return 0;
}


你可能感兴趣的:(IO)