630. Course Schedule III(贪心)

1.题目描述

There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.

Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.

Example:

Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
Output: 3

Explanation:
There’re totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.

2.代码

分析:本题的贪心策略在于尽可能地在同一长度的时间内多参加课程。
方法:按课程结束时间的先后进行排序,保证了在课程结束之前尽可能多地参加;如果某个课程 A 的结束时间在课程B之前,但是 A 的跨时比B长,且使得 B 无法参加,那么应该放弃参加A而选择参加 B B是绝对可以代替 A 的,因为B A <script type="math/tex" id="MathJax-Element-1122">A</script>晚结束),这样争取了更多时间可以参与其他课程。
关键:如何维护那些目前已参加课程的跨时长度,且能快速找到一个最长的跨时!
提示:使用multiset,支持less排序,且可以重复,使用平衡二叉树组织的multiset查找快速。

class Solution {
public:
    int scheduleCourse(vector<vector<int> >& courses) {
        sort(courses.begin(), courses.end(), comp);
        int currentEnd = 0;
        multiset<int> takens;
        vector<int> v;
        for(int i = 0;i < courses.size(); ++i) {
            v = courses[i];
            if(currentEnd + v.front() <= v.back()) {
                takens.insert(v.front());
                currentEnd += v.front();
            } else if(*takens.rbegin() >= v.front()) {
                currentEnd += v.front() - *takens.rbegin();
                takens.erase(--takens.end());
                takens.insert(v.front());
            }
        }
        return takens.size();
    }
    //若结束时间相同,则跨时短的在前面
    static bool comp( const vector<int>& v1, const vector<int>& v2) {
        if(v1.back() < v2.back()) {
            return true;
        } else if(v1.back() == v2.back()) {
        //这里不能是 <=, 否则出现运行错误,我也不知道原因
            if(v1.front() < v2.front()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
};

联系邮箱:sysuygm@163.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值