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].
Input
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.
Output
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.
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
问题分析:典型区间覆盖问题,思路贪心。先要进行预处理,每个区间在【0,m】外的部分应该预先被切掉。然后把各区间按照左端点从小到大排序,如果最小的那个区间大于0,则无解,否则选择起点小于等于0的最长区间,选择此区间后,新的起点应该更新为该区间的右端点。
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
struct section
{
int right;
int left;
}q[100005];
int cmp(section a, section b)
{
return a.left < b.left ;
}
int n[100005];
int main()
{
int t;
int s ;
cin >> t;
while (t--)
{
int m;
cin >> m;
int a, b;
int j = 0;
while (cin >> a >> b && (a + b))
{
if (b <= 0 || a >= m);
else
{
q[j].left = a;
q[j++].right = b;
}
}
sort(q, q + j, cmp);//排序
/*for (int i = 0; i < j; i++)
{
cout << q[i].left << " " << q[i].right << endl;
}*/
if (q[0].left > 0)//如果第一个区间左端点大于0则无解
{
cout << 0 << endl;
if (t != 0)
cout << endl;
// cout << 4 << endl;
continue;
}
else
{
int nr = 0;//用来保存左端点小于起点的区间的右端点中的最大值
int nl = 0;//更新的起点
s = 0;
while (nl < m)
{
int number;
nr = nl;
for (int i = 0; i < j; i++)
{
if (nr < q[i].right&&q[i].left<=nl)
{
nr = q[i].right;
number = i;
}
}
if (nr == nl)
{
s = 0;
//cout << 4 << endl;
break;
}
n[s] = number;
s++;
nl = nr;//更新起点
}
}
cout << s << endl;
//cout << 4 << endl;
for (int i = 0; i < s; i++)
{
cout << q[n[i]].left << " " << q[n[i]].right << endl;
}if (t != 0)
cout << endl;
memset(q, 0, sizeof(q));
memset(n, 0, sizeof(n));
}
}