#include #include struct Interval { float start; float finish; float value; }; struct Intervals { struct Interval * items; int number; }; struct Intervals read_intervals(char * filename) { struct Intervals result; result.number = 0; result.items = 0; FILE * handle = fopen(filename, "rb"); if (handle == 0) { printf("cannot open %s\n", filename); return result; } fscanf(handle, "%d", &(result.number)); result.items = malloc(sizeof(struct Interval) * (1 + result.number)); // printf("number = %d\n", result.number); result.items[0].start = 0; result.items[0].finish = 0; result.items[0].value = 0; int counter; for (counter = 1; counter <= result.number; counter++) { float start, finish, value; fscanf(handle, "%f %f %f", & start, & finish, & value); result.items[counter].start = start; result.items[counter].finish = finish; result.items[counter].value = value; // printf("%3d: start = %5.1f, finish = %5.1f, value = %5.1f\n", counter, start, finish, value); if (finish < result.items[counter-1].finish) { printf("error, intervals are not sorted\n"); exit(1); } } return result; } int * compute_last_complete(struct Intervals intervals) { int * last_complete = malloc(sizeof(int) * (1+intervals.number)); last_complete[0] = 0; int counter, second_counter; for (counter = 1; counter <= intervals.number; counter++) { float start = intervals.items[counter].start; second_counter = counter - 1; while(1) { float finish = intervals.items[second_counter].finish; if (finish <= start) { last_complete[counter] = second_counter; // printf(" last_complete[%d] = %d\n", counter, second_counter); break; } second_counter--; } } return last_complete; } float wis(struct Intervals intervals) { int * last_complete = compute_last_complete(intervals); float * solutions = malloc(sizeof(float) * (1+ intervals.number)); solutions[0] = 0; int counter; for (counter = 1; counter <= intervals.number; counter++) { float solution_without = solutions[counter - 1]; float value = intervals.items[counter].value; float solution_with = solutions[last_complete[counter]] + value; float best_value = solution_without; if (solution_with > best_value) best_value = solution_with; solutions[counter] = best_value; // printf("counter %4d: solution_without = %6.1f, solution_with = %6.1f, best = %6.1f\n", // counter, solution_without, solution_with, best_value); } float result = solutions[intervals.number]; free(last_complete); free(solutions); return result; } int main() { struct Intervals intervals = read_intervals("wis1.txt"); float f = wis(intervals); printf(" wis = %f\n", f); free(intervals.items); return 0; }