Question:
There are N closed intervals [ai, BI] On the number axis. Select as few intervals as possible to overwrite a specified line segment [0, m]
Algorithm:
[Start, end] indicates the covered range.
This is greedy.
Sort the intervals first by the Left endpoint from small to large, and update start to end. If interval 1 is on the right end of start, there is no solution, because other intervals are not likely to overwrite
In the remaining range that can overwrite the start, select the range that can overwrite the rightmost end and update the end, and record it in the path. Exit the loop if the end has covered m
If end does not overwrite start after traversing all intervals, there is no solution
Finally, follow the path output range recorded in parh.
1 //#define LOCAL 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 using namespace std; 7 8 const int maxn = 100000 + 10; 9 10 struct Range11 {12 int a, b;13 inline bool operator< (const Range& rhs) const14 {15 return a < rhs.a || (a == rhs.a && b < rhs.b);16 }17 }ranges[maxn];18 int path[maxn];19 20 int main(void)21 {22 #ifdef LOCAL23 freopen("10020in.txt", "r", stdin);24 #endif25 26 int T;27 scanf("%d", &T);28 while(T--)29 {30 int a, b, m, n = 0;31 scanf("%d", &m);32 while(scanf("%d%d", &a, &b) == 2)33 {34 if(a == 0 && b == 0) break;35 if(a > m) continue;36 if(a < 0) a = 0;37 ranges[n].a = a;38 ranges[n++].b = b;39 }40 sort(ranges, ranges + n);41 int minCover = 0;42 int start = 0, end = 0;43 for(int i = 0; i < n; )44 {45 start = end;46 if(ranges[i].a > start)47 break;48 while(i < n && ranges[i].a <= start)49 {50 if(ranges[i].b > end)51 {52 end = ranges[i].b;53 path[minCover] = i;54 }55 ++i;56 }57 ++minCover;58 if(end >= m) break;59 }60 if(end < m) minCover = 0;61 printf("%d\n", minCover);62 for(int i = 0; i < minCover; ++i)63 printf("%d %d\n", ranges[path[i]].a, ranges[path[i]].b);64 if(T)65 printf("\n");66 }67 return 0;68 }
Code Jun
Ultraviolet A 10020 (minimum range coverage) minimal coverage