Minimal coverage
The Problem
Given several segments of line (int the X axis) with coordinates [Li, Ri]. you are to choose the minimal amount of them, such they wocould completely cover the segment [0, M].
The Input
The first line is the number of test cases, followed by a blank line.
Each test case in the input shoshould 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.
The Output
For each test case, in the first line of output your programm shocould 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), shocould be printed in the same format as in the input. pair "0 0" shocould not be printed. if [0, M] can not be covered by given line segments, your programm shold print "0" (without quotes ).
Print a blank line between the outputs for two consecutive test cases.
Sample Input
2
1
-1 0
-5-3
2 5
0 0
1
-1 0
0 1
0 0
Sample Output
0
1
0 1
A given M and some intervals [Li, Ri]. Select several intervals that can completely cover the [0, M] range. The minimum number is required .. If output 0 cannot be overwritten.
Idea: greedy thoughts .. Sort the intervals by Ri in ascending order. Then we encounter a satisfying [Li, Ri], and then update and narrow the range .. Until it is completely overwritten.
Note: [Li, Ri] only the condition that the Li is less than or equal and the Ri is greater than the left end of the current coverage interval is met. To be selected.
Code:
# Include <stdio. h> # include <string. h ># include <algorithm> using namespace std; int t; int start, end, qn, outn; struct M {int start; int end;} q [100005], out [100005]; int cmp (M a, M B) {// return. end> B. end ;}int main () {scanf ("% d", & t); while (t --) {qn = 0; outn = 0; start = 0; scanf ("% d", & end); while (~ Scanf ("% d", & q [qn]. start, & q [qn]. end) & q [qn]. start + q [qn]. end) {qn ++;} sort (q, q + qn, cmp); while (start <end) {int I; for (I = 0; I <qn; I ++) {if (q [I]. start <= start & q [I]. end> start) {start = q [I]. end; // Update Interval out [outn ++] = q [I]; break ;}} if (I = qn) break; // if no interval meets the conditions, it ends directly .} If (start <end) printf ("0 \ n"); else {printf ("% d \ n", outn); for (int I = 0; I <outn; I ++) printf ("% d \ n", out [I]. start, out [I]. end) ;}if (t) printf ("\ n") ;}return 0 ;}