题目摘要:Since milk packaging is such a lowmargin business, it is important to keep the price of the raw product (milk) aslow as possible. Help Merry Milk Makers get the milk they need in the cheapestpossible manner.
The Merry Milk Makers company has severalfarmers from which they may buy milk, and each one has a (potentially)different price at which they sell to the milk packing plant. Moreover, as acow can only produce so much milk a day, the farmers only have so much milk tosell per day. Each day, Merry Milk Makers can purchase an integral amount ofmilk from each farmer, less than or equal to the farmer's limit.
Given the Merry Milk Makers' dailyrequirement of milk, along with the cost per gallon and amount of availablemilk for each farmer, calculate the minimum amount of money that it takes tofulfill the Merry Milk Makers' requirements.
Note: The total milk produced per day bythe farmers will be sufficient to meet the demands of the Merry Milk Makers.
题目大意:一家牛奶公司向奶农收购牛奶,要求最低收购量为N,而他们公司有M个奶农可向其收购牛奶。由于奶牛的产奶量有限,所以每个奶农所能提供的牛奶量有限,而每个奶农向这个公司索要的价钱也不一样,现要求这个公司完成所要达成的最低收购量N所花的最少钱。
输入输出要求:
INPUT FORMAT
Line 1: | Two integers, N and M. |
Lines 2 through M+1: | The next M lines each contain two integers, Pi and Ai. |
OUTPUT FORMAT
A single line with a single integer that isthe minimum price that Merry Milk Makers can get their milk at for one day.
输入输出样例:
SAMPLE INPUT
100 5
5 20
9 40
3 10
8 80
6 30
SAMPLE OUTPUT
630
解题思路:将价格排序,从最低价格开始收购,数量满足条件即可。
代码:
#include<iostream>
using namespace std;
int price[5005];
int count[5005];
void Sort(int Began[],int End[],int n)
{
inti,j,k;
inttemp1,temp2;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
{
if(Began[j]<Began[k])
{
k=j;
}
}
if(k!=i)
{
temp1=Began[k];
Began[k]=Began[i];
Began[i]=temp1;
temp2=End[k];
End[k]=End[i];
End[i]=temp2;
}
}
}
int main()
{
intN,M;
inti;
intsum=0;
intpos=0;
intans=0;
cin>>N>>M;
for(i=0;i<M;i++)
cin>>price[i]>>count[i];
Sort(price,count,M);
for(i=0;i<M;i++)
{
sum+=count[i];
if(sum==N)
{
pos=i;
break;
}
elseif(sum>N)
{
pos=i-1;
break;
}
}
for(i=0;i<=pos;i++)
{
N-=count[i];
ans+=price[i]*count[i];
}
if(N==0)
cout<<ans<<endl;
else
cout<<ans+N*price[i]<<endl;
return0;
}
解题感想:要注意不一定要把每个奶农的所有牛奶都收购走,以样例为例,价格排序后为3,5,6,8,9,对应的数量为10,20,30,80,40。要求收购量为100,也就是买光前三个奶农的所有牛奶,然后向第四个奶农买数量为40的牛奶即可。