simple task scheduling problem
Today we will talk about task scheduling problem using greedy thinking. In fact, greedy algorithm is quite uncommon, for most problems in our life can not be solved just by greedy algorithm. But here is one, a simple task scheduling problem. Let’s solve it!
Description:.
Suppose you have a list of work to do. For each task, it starts from b[i] and ends at e[i]. Now give you the number of the whole tasks. You’ve already know that you can not do multiple tasks at the same time, but you want to participate in the most tasks in this period of time to get more money(hhh). So, how many tasks can you participate in at most?
sample
input
5
1 3
2 5
4 7
6 9
8 10
output
3
How to think this problem?
Always choose the task which ends earliest.
We can think like this: at the same time, we choose the task which begins ealier. That is to say, we make our time much more compact. Hence, there won’t be any method to do more tasks.
Code
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct node{
int begin;
int end;
}Node;
Node data[10000];
bool cmp(const Node& a,const Node& b){
return a.end<b.end;
}
int main(void){
int n,count=0;
cin>>n;
for(int i=0;i<n;i++){
cin>>data[i].begin>>data[i].end;
//cin>>begin[i]>>end[i];
}
sort(data,data+n,cmp);
int workEnd=0;
for(int i=0;i<n;i++){
if(data[i].begin>workEnd){
count++;
workEnd=data[i].end;
}
else{
continue;
}
}
cout<<count<<endl;
}