天天看点

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:

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 = ;
        multiset<int> takens;
        vector<int> v;
        for(int i = ;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;
        }
    }
};
           
联系邮箱:[email protected]