Minimal coverage
Given several segments of line (int the X axis) with coordinates [Li,Ri]. You are to choose the minimal amount of them, such they would completely cover the segment [0,M].
The first line is the number of test cases, followed by a blank line.
Each test case in the input should contains an integer M(1<=M<=5000), followed by pairs "Li Ri"(|Li|, |Ri|<=50000, i<=100000), each on a separate line. Each test case of input is terminated by pair "0 0".
Each test case will be separated by a single line.
For each test case, in the first line of output your programm should print the minimal number of line segments which can cover segment [0,M]. In the following lines, the coordinates of segments, sorted by their left end (Li), should be printed in the same format as in the input. Pair "0 0" should not be printed. If [0,M] can not be covered by given line segments, your programm should print "0"(without quotes).
Print a blank line between the outputs for two consecutive test cases.
2 1 -1 0 -5 -3 2 5 0 0 1 -1 0 0 1 0 0
0 1 0 1
/** * 贪心: 区间覆盖问题。。算很水的了吧 * 把所有区间段存在struct中, 再对L进行升序排序。 在选择区间的时候就要用到贪心思想了: * 遍历已经排序处理好后的区间线段数组, 先对符合条件的,也就是可以选的区间进行处理,也就是说 * 到遍历到一个区间,其L <= curL, R > curL ,这样的区间段是可以选择的,但不一定要选!! * 要选的是,在都可选的区间段里选择一个 R 最大的,所以用一个变量curMax 来记录这些区间能够达到的最右边。 * 一直到下一个区间段是不能选取的时候,再把curMax 替换curL. 记录下选取的坐标curPos ,记录在一个ans[]数组里。 * 在一次贪心地遍历之后就能够生成一个ans[] 即为最后答案。。 * 还有一个就是如何判断这些区间段不能够覆盖[0, M] , 在遍历的时候如果所能选取的剩下的区间段的 * 最小的L都比curL大的话,必然是有一部分区间(也就是区间(curL, L))你是不能够覆盖的,所以输出0; */ #include <cstdio> #include <cstring> #include <cmath> #include <stack> #include <string> #include <queue> #include <map> #include <algorithm> #define INF 0x7fffffff using namespace std; struct Segment { int L, R; bool operator < (const Segment &a) const { if(L != a.L) return L < a.L; else return R > a.R; } } segments[100005]; int main() { int cases; scanf("%d", &cases); while(cases--) { int M, n; scanf("%d", &M); for(n = 0; ; n ++) { scanf("%d%d", &segments[n].L, &segments[n].R); if(!segments[n].L && !segments[n].R) break; } sort(segments, segments + n); int i, curL = 0, isOk = false, cnt = 0, curMax = 0, curPos; int ans[100005], ansNum; for(i = 0, ansNum = 0; i < n; i ++) { if(segments[i].L > curL) { isOk = false; break;} if(segments[i].R > curL) { if(segments[i].R > curMax) { curMax = segments[i].R; curPos = i; } if(segments[i + 1].L > curL || i + 1 == n) { cnt ++; curL = curMax; curMax = 0; ans[ansNum ++] = curPos; } } if(curL >= M) { isOk = true; break; } } if(!isOk) { printf("0\n"); } else { printf("%d\n", cnt); for(i = 0; i < ansNum; i ++) { printf("%d %d\n", segments[ans[i]].L, segments[ans[i]].R); } } if(cases) printf("\n"); } return 0; }