#include <stdio.h>
#include <stdlib.h>
struct Interval {
int start;
int end;
};
int compare(const void *a, const void *b) {
return ((struct Interval *)a)->end - ((struct Interval *)b)->end;
}
int maxNonOverlappingIntervals(struct Interval intervals[], int n) {
if (n <= 0) {
return 0;
}
qsort(intervals, n, sizeof(struct Interval), compare);
int count = 1;
int end = intervals[0].end;
for (int i = 1; i < n; i++) {
if (intervals[i].start > end) {
count++;
end = intervals[i].end;
}
}
return count;
}
int main() {
struct Interval intervals[] = {{1, 2}, {2, 4}, {3, 5}, {5, 7}, {8, 9}};
int n = sizeof(intervals) / sizeof(intervals[0]);
int result = maxNonOverlappingIntervals(intervals, n);
printf("最多能选出%d个不相交的区间\n", result);
return 0;
}