贪心算法刷题笔记(C++)

前言

本帖主要是记录在LeetCode刷题笔记,持续更新中。

会议安排

    // 1.会议室安排,输入为每个会议的起止时间,会议有冲突,要求尽可能多的会议。
        struct Agent{
            Agent(){
                name = "invalid";
                start = 0;
                end = 0;
            }
            Agent(std::string a, int b, int c){
                name = a;
                start = b;
                end = c;
            }
            std::string name;
            float start;
            float end;
            bool operator<(const Agent& b) const{
                return this->end < b.end;
            } 
        };
        std::vector<Agent> BestAgentArrange(std::vector<Agent> agents, float start){
            std::sort(agents.begin(), agents.end());// 按照结束时间的早晚排序
            std::vector<Agent> res;
            for(auto ele : agents){
                if(ele.start > start){
                    res.push_back(ele);
                    start += ele.end; //上一会议的结束时间作为开始时间
                }
            }
            return res;
        }

拼凑字符串

// 2.拼凑字符串使得字典数最小
    struct MyCompareDict{
        bool operator()(std::string& lhs, std::string& rhs){
            return lhs + rhs < rhs + lhs;
        }
    };
    
    std::string MinDictMerge(std::vector<std::string> ss){
        std::string res;
        sort(ss.begin(), ss.end(), MyCompareDict());
        for(auto ele : ss){
            res += ele;
        }
        return res;
    }

Hulfman编码

    // 3.Hulfman编码 要求list分割黄金,使得分割成本最低
    int HulfmanCode(const std::vector<int>& list){
        int res = 0;
        int cur = 0;
        std::priority_queue<int> temp(list.begin(),list.end());
        while(temp.size() > 1){
            cur = temp.top();
            temp.pop();
            cur += temp.top();
            temp.pop();
            res += cur;
        }
        return res;

    }

总结

局部最优->全局最优,代码都很短。

解题技巧:
1,举例全排列,暴力解法,即写一个对数器,
2,脑补几个贪心算法,用1验证,
3,不要纠结算法推导,证明较难,费时间。

局部最优并保证传递性(数学归纳法),最后对算法的结果后验:假设法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值