区间覆盖问题,刘汝佳小白书P154页有详细思路;
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef struct
{
int x,y;
}P;
P p[110000];
int cmp(P p1,P p2)
{
if(p1.x==p2.x)
return p1.y<p2.y;
return p1.x<p2.x;
}
int main()
{
int i,j,k,t,m,ans[110000],cnt;
scanf("%d",&t);
while(t--)
{
scanf("%d",&m);
k=0;
while(1)
{
int x,y;
scanf("%d%d",&x,&y);
if(!x&&!y)
break;
p[k].x=x; p[k].y=y;
k++;
}
sort(p,p+k,cmp);
cnt=0;
int left=0,right,flag=0;
for(i=0;i<k;)
{
right=0;
while(p[i].x<=left&&i<k)
{
if(p[i].y>right)
{
right=p[i].y;
j=i;
}
i++;
}
if(right==0)
break;
left=right;
ans[cnt++]=j;
if(right>=m)
{
flag=1;
break;
}
}
if(!flag)
{
printf("0\n");
if(t)
printf("\n");
continue;
}
printf("%d\n",cnt);
for(i=0;i<cnt;i++)
printf("%d %d\n",p[ans[i]].x,p[ans[i]].y);
if(t)
printf("\n");
}
return 0;
}