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;
}
本文探讨使用贪心算法解决简单任务调度问题。任务开始时间b[i]和结束时间e[i]已知,目标是在同一时间内参与最多的任务。贪心策略是始终选择最早结束的任务,以使时间更紧凑,确保任务数量最大化。
1509

被折叠的 条评论
为什么被折叠?



