Greedy Interval Scheduling problem

Problem description

  We have a day to work and we have different kinds works do to which has start-time and end-time. We have to choose the different works so that we can achieve the maximum number of minutes in a day to work. Chosen works should not overlaps to each other.

Ex-1:

  Start-Time End-Time
  W1: 6:00 9:30
  W2: 9:00 12:30
  W3: 12:00 14:30
  W4: 10:00 10:30
  W5: 11:00 13:30
  Solution: W1 + W4 + W3(or W5)

Ex-2:

  Start-Time End-Time
  W1: 6:00 8:30
  W2: 9:00 11:00
  W3: 12:30 14:00
  W4: 8:00 9:00
  W5: 10:30 14:00
  W6: 9:00 11:30
  Solution : W1 + W6 + W3 = 390min

Pseudo-code

Sort jobs by finish times so that f1 <= f2 <= ... <= fn.
select a task ——>A 
for j = 1 to n {
   if (job j compatible with A)
      A and {j} ——> A
}
return A  

Time complexity

  sortO(nlogn) +scanO(n) =O(nlogn)

Code

//区间调度
/*
问题描述:有N项工作,每项工作有开始时间si和结束时间ti,让你选择最多的工作,工作之间不存在时间交叉。
输入:
1 3
5
7
9
10
输出:
*/
#include<iostream>
#include<algorithm>
 
using namespace std;
const int MAX = 100000;
int N, s[MAX], t[MAX];//输入,s开始时间,t结束时间 
pair<int, int> itv[MAX];//用于对工作排序的pair数组
 
int main()
{
    cin>>N;
    int i;
    for(i=0;i<N;i++) cin>>itv[i].second>>itv[i].first;//便于以结束时间排序,所以改存顺序
        /*cin>>s[i]>>t[i];*/
    sort(itv, itv + N);
 
    int ans = 0, t = 0;
    for(i = 0; i < N; i++){
        if(t < itv[i].second){
            ans++;
            t = itv[i].first;
        }
    }
 
    cout<<ans<<endl;
 
    system("pause");
    return 0;
}
 
/*
贪心算法之所以能用,是基于以“结束时间最早”为前提的。但是这是需要你分析和证明的,你要先想明白为什么
按结束时间最早排序才是正确的。
1.因为结束时间最早,所以取相同数量的工作肯定它最早结束或至少不晚。
2.如果后面还有工作,那么加入到结束最早算法的空间更大。
因此就不会存在比它更多工作的可能。
*/

Ref

1、区间调度(贪心).
2、区间调度问题.
3、贪心算法——区间调度问题.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值