您的位置:首页 > 其它

贪心区间调度 Greedy interval scheduling problem

2013-12-14 01:32 204 查看
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

//区间调度
/*
问题描述:有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:
http://www.cnblogs.com/littlehoom/p/3430174.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: