贪心算法的应用

考虑最大利润

输入:种类数、需求量、各种类的库存量、各种类的总价

输出:最大利润

cpp 复制代码
#include <iostream>
#include <algorithm>//调用sort排序
using namespace std;
struct mooncake{
    double store;
    double price;
    double tprice;
}cake[1000];
bool cmp(mooncake a,mooncake b)
{
return a.price>b.price;
}
int main(){
    int kinds;
    double needs,profits=0;
    cin>>kinds>>needs;
    for(int i=0;i<kinds;i++)
    cin>>cake[i].store;
    for(int i=0;i<kinds;i++)
    {
        cin>>cake[i].tprice;
        cake[i].price=cake[i].tprice/cake[i].store;
    }
    sort(cake,cake+kinds,cmp);//由大到小排序
    for(int i=0;i<kinds;i++){
        if(cake[i].store<=needs)//供应充足
        {
            needs-=cake[i].store;//更新需求量
            profits=cake[i].tprice;
        }else{//供应不足:一定要手动结束,否则会继续循环
            profits+=cake[i].price*needs;//由单价一个个算出 
            break;//手动结束
        }
    }
    cout<<profits;
    return 0;
}

考虑最小数

输入:0-9位数的次数

输出:由该数所组成的最小数

cpp 复制代码
#include <iostream>
using namespace std;
int main(){
    int count[10];//分别记录0-9的个数
    for(int i=0;i<10;i++)
    cin>>count[i];
    for(int i=1;i<10;i++)//先确定首位
        if(count[i]>0)
        {
            cout<<i;
            count[i]--;
            break;
    }
    //直接由0-9一个个输出
    for(int i=0;i<10;i++)//循环各个位数
    for(int j=0;j<count[i];j++)//判断每个位数的次数 
    cout<<i;
    return 0;
}

统计不相交的区间个数-区间贪心

输入:区间个数、各区间的左右端点

输出:不相交的区间个数

cpp 复制代码
#include <iostream>
#include <algorithm>//sort方法
using namespace std;
struct interval{//定义区间结构体
    int left;
    int right;
}inter[100];
bool cmp(interval a,interval b){
    if(a.left!=b.left) return a.left>b.left;//左端点由大到小排序
    else return a.right<b.right;//右端点由小到大排序
}
int main(){
    int n;
    int count=1;//记录不相交的区间个数 
    cin>>n;
        for(int i=0;i<n;i++)
        cin>>inter[i].left>>inter[i].right;
    sort(inter,inter+n,cmp);
    int lastval=inter[0].left;//存最大的:最右端的左端点
    for(int i=1;i<n;i++)
        if(inter[i].right<=lastval)//右端点小于左端点,说明这两个区间不相交
        {
            lastval=inter[i].left;//更新左端点
            count++;
    }else count--;
    cout<<count<<endl;
    return 0;
}

贪心算法:考虑当前情况下局部最优的策略,从而使全局达到最优的方法

相关推荐
hsjkdhs2 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
立志成为大牛的小牛2 小时前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光3 小时前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
StarPrayers.4 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
爱吃橘的橘猫4 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式
235164 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
weixin_307779136 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
柳安忆6 小时前
【论文阅读】Sparks of Science
算法
web安全工具库6 小时前
从课堂笔记到实践:深入理解Linux C函数库的奥秘
java·数据库·算法
爱编程的鱼7 小时前
C# 变量详解:从基础概念到高级应用
java·算法·c#