题目描述 Description
好吧,新年到了,要买贺年卡了
我们知道要买m张贺年卡,且看中n家店铺,每家店铺的存货量和价格不同
我们最少要花多少钱?
输入描述 Input Description
包括n+1行
第一行,m和n
以下n行,每行两个整数,代表该店铺的贺年卡单价与存货量
输出描述 Output Description
仅一个整数,表示我们最少要花多少钱
样例输入 Sample Input
10 4
4 3
6 2
8 10
3 6
样例输出 Sample Output
36
数据范围及提示 Data Size & Hint
样例解释:
先将最后一家买空(3元*6=18元)
再将第一家买空(4元*3=12元)
再从第二家买一张(6元*1=6元)
刚好十张,总价格36元
保证结果在长整型以内且总存货量不少于m,保证有且只有一个最优解
0<m,n<=1000
贪心算法
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef struct node
{
int x,y;
}No;
bool comper(No a,No b)
{
if(a.x<b.x)return 1;
else if(a.x==b.x&&a.y>b.y)return 1;
else return 0;
}
int main()
{
int x,y;
No stor[1001]={0};
scanf("%d%d", &x,&y);
int i;
for(i=0;i<y;i++)
{
scanf("%d%d", &stor[i].x, &stor[i].y);
}
sort(stor,stor+y,comper);
int sum=0;
for(i=0;i<y;i++)
{
if(x-stor[i].y>=0)
{
sum+=stor[i].x*stor[i].y;
x-=stor[i].y;
}
else
{
sum+=x*stor[i].x;
break;
}
}
printf("%d\n",sum);
return 0;
}