Basic thought:In each iteration,we will choose the "best" solution at that moment,this "best" solution may not be result to a bestfinal solution.But in some problems,it will lead to a optimal result.
Advantage:Simple,efficient
Disadvantage:May be not correct andoptimal.
Now,there is a classic problem we willanalysize(Interval Scheduling)
Interval Scheduling:
given condition
1__ Job j(0<j<9) starts at time Sjand finishes at Fj
2__ Two jobs compatible if they don'toverlap
question:
How to find a maximum subset of mutuallycompatible jobs.
graph is shown below
Step 1:
wewill sort jobs in some order with 4 measure.
1,[Earliest start time] Consider jobs in ascending order of starttime Sj
theorder will be:a(1-6),b(2-4),c(3-5),d(3-8),e(4-7),f(5-9),g(6-10),h(8-11).(job(starttime-finish time)).
the solution is "ah" with GreedAlgorithm.
2,[Earliest finish time] Consider jobs in ascending order of finishtime Fj.
theorder will be:bcaedfh
thesolution is "beh" with Greed Algorithm.
3,[Shortest interval] Consider jobs in ascending order of intervallength Fj-Sj.
theorder will be:bcehfgda
thesolution is "beh" with Greed Algorithm.
4,[Fewest conflicts] For each job, count the number of conflictingjobs Cj, Schedule in ascending orderof conflicts Cj.
theorder will be:hbcgaefd.
thesolution is "hbe" with Greed Algorithm.
Now program the code considering jobs inincrasing order of finish time.
#include <stdio.h>
#include <stdlib.h>
typedef struct job_task{
char task;
int start_time;
int finish_time;
struct job_task *next;
}job_task;
typedef job_task* job;
static job a,b,c,d,e,f,g,h,head,p;
void assignment(job jo,char c,int starttime,int finishtime){
p->next = jo;
jo->task = c;
jo->start_time = starttime;
jo->finish_time = finishtime;
jo->next=NULL;
p = jo;
return;
}
void initial(){
head = (job)malloc(sizeof(job_task));
b = (job)malloc(sizeof(job_task));
c = (job)malloc(sizeof(job_task));
a = (job)malloc(sizeof(job_task));
d = (job)malloc(sizeof(job_task));
e = (job)malloc(sizeof(job_task));
f = (job)malloc(sizeof(job_task));
g = (job)malloc(sizeof(job_task));
h = (job)malloc(sizeof(job_task));
p = head;
head->start_time=0;
head->finish_time=0;
return;
}
void get_subset(){
job jo;
p = head;
jo = p->next;
while(jo != NULL){
if(jo->start_time >= p->finish_time){
p->next = jo;
p=jo;
}
jo = jo->next;
}
return;
}
void print(){
job jo = head->next;
while(jo!=NULL){
printf("%c ",jo->task);
jo = jo->next;
}
}
void main(){
initial();
assignment(b,'b',2,4);
assignment(c,'c',3,5);
assignment(a,'a',1,6);
assignment(e,'e',4,7);
assignment(d,'d',3,8);
assignment(f,'f',5,9);
assignment(g,'g',6,10);
assignment(h,'h',8,11);
get_subset();
print();
}