题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2187
类型:贪心
代码:
#include<stdio.h>
#include<stdlib.h>
struct cc
{
int p;
int h;
} d[1005];
int comp(void const *a,void const *b)
{
struct cc *p1 = (struct cc *)a;
struct cc *p2 = (struct cc *)b;
return p1->p-p2->p;
}
int main()
{
int i,m,n,c;
float t;
scanf("%d",&c);
while(c--)
{
t=0;
scanf("%d %d",&n,&m);
for(i=0; i<m; i++)
{
scanf("%d %d",&d[i].p,&d[i].h);
}
qsort(d,m,sizeof(struct cc),comp);//按照单价递排序
for(i=0;i<m;i++)
{
if(d[i].p*d[i].h >= n && n!=0)//把第i总米全买了,如果钱不够则只买当前钱数能买到的最大值
{
t = t + n/(d[i].p*1.0);
n = 0;
}
else//如果钱够则计算出剩余的钱做下一次循环,直到剩余的钱n为0退出
{
if(n==0)break;
t = t + d[i].h*1.0;
n = n - d[i].p*d[i].h;
}
}
printf("%.2f\n",t);
}
return 0;
}
分析:现学现卖,今天刚学的。单价递增排序,从上到下每次都买足够多的东西,如果钱不够则把钱全部买这样东西,如果钱多则用剩下的钱买下一种东西,直到钱数为0,退出