贪心法是求解一类最优划问题的方法,它总是考虑在当前状态下局部最优(较优)的策略,来使得全局的结果达到最优(较优)
举例
销售月饼
#include <cstdio>
#include <algorithm>
using namespace std;
struct mooncake{
double store;
double sell;
double price;
}cake[1010];
bool cmp(mooncake a,mooncake b){
return a.price>b.price;
}
int main() {
int n;
double D;
scanf("%d%f",&n,&D);
for (int i = 0; i < n; i++) {
scanf("%lf",&cake[i].store);
}
for (int i = 0; i < n; i++) {
scanf("%lf",&cake[i].sell);
cake[i].price=cake[i].sell/cake[i].store; //计算单价
}
sort(cake,cake+n,cmp); //按单价从高到低排序
double ans=0; //收益
for (int i = 0; i < n; i++) {
if(cake[i].store<=D){ //需求量大于库存量
ans+=cake[i].sell;
}else{ //需求量小于库存
ans+=cake[i].price*D;
break;
}
}
printf("%0.2f\n",ans);
return 0;
}
组成最小的数字
#include <cstdio>
int main() {
int count[10];
for (int i = 0; i < 10; i++) {
scanf("%d",&count[i]);
}
for(int i=1;i<10;i++){
if(count[i]>0){
printf("%d",i);
count[i]--;
break;
}
}
for(int i=0;i<10;i++){
for(int j=0;j<count[i];j++){
printf("%d",i);
}
}
return 0;
}
区间贪心
区间不相交问题
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=110;
struct Inteval{
int x,y;
}I[maxn];
bool cmp(Inteval a,Inteval b){
if (a.x!=b.x)
return a.x>b.x;
else return a.y<b.y;
}
int main() {
int n;
while(scanf("%d",&n),n!=0){
scanf("%d%d",&I[i].x,&I[i].y)
}
return 0;
}