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]. InputThe 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. OutputFor each test case, in the first line of output your programm should print the minimal number of linesegments which can cover segment [0, M]. In the following lines, the coordinates of segments, sortedby their left end (Li), should be printed in the same format as in the input. Pair ‘0 0’ should not beprinted. If [0, M] can not be covered by given line segments, your programm should print ‘0’ (withoutquotes).Print a blank line between the outputs for two consecutive test cases. Sample Input21-1 0-5 -32 50 01-1 00 10 0Sample Output010 1
思路:
把所有区间从小到大排序,每次进行比较,找区间右边尽量大的,直到覆盖整个区间
源代码:
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 #define maxn 100000+5 7 int M; 8 struct Seg{ 9 int left;10 int right;11 friend bool operator<(const Seg&a, const Seg&b)12 {13 if (a.left != b.left)14 return a.left b.left; //现在还不懂为什么要这样/(ㄒoㄒ)/~~16 17 }18 }q[maxn];19 int ai[maxn];20 int main()21 {22 int T;23 cin >> T;24 while (T--)25 {26 int flag = 0;27 cin >> M;28 int Index = 0;29 while (cin >> q[Index].left >> q[Index].right)30 {31 32 if (q[Index].left==0&&q[Index].right==0)33 break; 34 if (q[Index].right > 0) ++Index; //把区间右边大于0的才存进去35 }36 37 sort(q, q + Index);38 if (q[0].left > 0) //第一个的左边都大于0,表示没有区间可以覆盖目标区间39 {40 cout << "0\n";41 if (T) //不是最后一组数据要求输出空行42 cout << endl;43 continue;44 45 }46 int cur = 0;47 int j = -1;48 for (int i = 0; i < Index; i++)49 {50 if (q[i].left <= cur) //区间左边小于0的满足初步条件51 {52 if (j == -1)53 ai[++j] = i; 54 else if (q[i].right > q[ai[j]].right) //找区间右边大的55 ai[j] = i;56 }57 else58 {59 cur = q[ai[j]].right; //找区间右边尽量大的60 ai[++j] = i;61 }62 63 if (q[ai[j]].right >= M) //覆盖了整个区间64 {65 flag = 1;66 break;67 }68 69 }70 if (flag)71 {72 cout << j + 1 << endl;73 for (int i = 0; i <=j; i++)74 75 cout << q[ai[i]].left << " " << q[ai[i]].right << endl;76 77 }78 else79 80 cout << "0\n";81 if (T)82 cout << endl;83 84 }85 86 return 0;87 }