activity select problem(greedy algorithms)

时间:2022-02-02 13:27:03

many activities will use the same place, every activity ai has its'  start time si and finish time fi.let the number of activities to be as many as possible.

1. dynamic programming

use ak be a knife to cut the set activities into two parts and recursive to find the max subset

c[i,j](star after ai finish and finish before aj star) = max {1+c[i,k] + c[k,j]} or 0(haven't ak);

2.greedy programming

let ai ranked by their finish time. earlier finish time ranked front than the later.

then choose the activities by its finish time, keep they are not contradictory.

 public class activity_select {
int[] s = {1,3,0,5,3,5,6,8,8,2,12};
int[] f = {4,5,6,7,9,9,10,11,12,14,16};
private static class activity{
private int sta ;
private int fin ;
public activity(){
sta = 0;
fin = 0;
}
} public activity[] select(){
activity[] act = new activity[s.length];
for(int i = 0;i<s.length;i++){ //initial
act[i] = new activity();
act[i].sta = s[i];
act[i].fin = f[i];
}
for(int i = 0;i<s.length;i++){ //insert sort from early fin to later fin
for(int j = i;j < s.length;j++){
if(act[i].fin > act[j].fin){
int testa = act[j].sta;
int tefin = act[j].fin;
act[j].sta = act[i].sta;
act[j].fin = act[i].fin;
act[i].fin = tefin;
act[i].sta = testa;
}
}
}
activity[] res = new activity[s.length];
res[0] = act[0];
int j = 0;
for(int i = 0;i < s.length -1;i++){
if(act[i+1].sta > res[j].fin){
res[++j] = act[i + 1];
}
}
activity[] res1 = new activity[j+1];
for(int i = 0;i <=j;i++){
res1[i] = res[i];
}
return res1;
} public static void main(String[] args){
activity_select ac = new activity_select();
activity[] a = ac.select();
int n = a.length;
for(int i = 0;i < n;i++){
System.out.println(a[i].sta + " " +a[i].fin);
}
} }