题意:小白的P(154)页,照着书上模拟就行了
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
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;
}