// Weighted interval scheduling. See Kleinberg & Tardos, chapter 6 #include #include #define TABSIZE (100) int n,s[TABSIZE],f[TABSIZE],v[TABSIZE],p[TABSIZE],M[TABSIZE]; int sPerm[TABSIZE]; // Indices ordered according to s[] int max(int x,int y) { if (x>y) return x; return y; } int orderBys(const void* xin, const void* yin) // Used to order array of indices according to values in another array. { int result; int *x,*y; x=(int*) xin; y=(int*) yin; result=s[(*x)]-s[(*y)]; if (result!=0) return result; return (*x)-(*y); // Breaks s value tie using the s subscripts. } int main() { int i,j,sum=0; scanf("%d",&n); for (i=1;i<=n;i++) scanf("%d %d %d",&s[i],&f[i],&v[i]); for (i=2;i<=n && f[i-1]<=f[i];i++) ; if (i<=n) { printf("Intervals not ordered by finish time %d\n",__LINE__); exit(0); } // Create table of indices to s, then sort in ascending ref order to s. for (i=0;i=0;i--) { while (j>=sPerm[i] || f[j]>s[sPerm[i]]) j--; p[sPerm[i]]=j; } /* // This is the slow version for the sort & merge above. for (i=1;i<=n;i++) { for (p[i]=i-1; p[i]>=0 && f[p[i]]>s[i]; p[i]--) ; } */ M[0]=0; for (i=1;i<=n;i++) M[i]=max(v[i]+M[p[i]],M[i-1]); printf(" i s f v p M\n"); for (i=1;i<=n;i++) printf("%3d %3d %3d %3d %3d %3d\n",i,s[i],f[i],v[i],p[i],M[i]); for (i=n;i>0; ) if (v[i]+M[p[i]]>=M[i-1]) { printf("Include interval %d\n",i); sum+=v[i]; i=p[i]; } else i--; printf("sum is %d\n",sum); }