[USACO1.3]混合牛奶 Mixing Milk
阿新 • • 發佈:2019-01-05
題目大意:
標題 from 洛谷
需要買N個單位的牛奶,有M個農民,每個農民的牛奶數量是固定的,但是他們給出的價格不同
請問最少用多少錢可以買到N個單位的牛奶
解題思路:
貪心
一遍排序選最便宜的
Accepted code:
#include<cstdio>
#include<algorithm>
using namespace std;
struct Milk {
int Price, Num;
}a[5005];
int price, sum, N, M;
bool cmp(Milk x, Milk y) {
return x.Price < y.Price;
}
int main() {
scanf("%d %d", &N, &M);
for (int i = 1; i <= M; i++)
scanf("%d %d", &a[i].Price, &a[i].Num);
sort(a+1, a+M+1, cmp); int i = 0;
while (sum < N) {
++i;
if (sum + a[i].Num > N) price += (N - sum) * a[i].Price, sum = N;
else price += a[i].Num * a[i].Price, sum += a[i].Num;
}
printf("%lld\n", price);
}