【Minimal coverage】【UVA - 10020】(区间排序,cmp)

版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/84660920

题目:

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

解题报告:最小区间覆盖问题,给定咱们一个数字m,问是否存在有限个线段,能够将它完全覆盖。

解题的思路就是:先筛出去右端点小于0的和左端点大于m的,然后看看是否有左端点小于0的或者右端点大于m的,如果有的话就可以继续寻找,按照x的第一升序,y的第二升序排列,看看有无这种线段,有的话,按照y的升序排列,之后存放到数组里,更新最右端点。依次进行,最后能够实现全部的线段查询完毕。

ac代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn =1e6+100;

struct node{
	int x,y;
}pot[maxn];

bool cmp(node a,node b)
{
	if(a.x==b.x)
		return a.y<b.y;
	else
		return a.x<b.x;
}
bool cmp1(node a,node b)
{
	return a.y<b.y;
}
int num[maxn*2];

int main()
{
	int t,m,i;
	cin>>t;
	while(t--)
	{
		int cnt=0;
		int flagx=0,flagy=0;
		int mcnt=0;
		scanf("%d",&m);
		for(cnt=0;;cnt++)
		{
			scanf("%d%d",&pot[cnt].x,&pot[cnt].y);
			if(!pot[cnt].x&&!pot[cnt].y)
				break;
			if(pot[cnt].y<=0||pot[cnt].x>=m)
				cnt--;
			else
			{
				if(pot[cnt].x<=0)
					flagx=1;
				if(pot[cnt].y>=m)
					flagy=1;
			}
		}
		int l=0,fi=0;
		if(flagx&&flagy&&cnt==1)
			printf("1\n%d %d\n",pot[0].x,pot[0].y);
		else if(flagx&&flagy)
		{
			sort(pot,pot+cnt,cmp);
			int ff=0;
			while(l<m)
			{
				for(i=fi;i<cnt;i++)
				{
					if(pot[i].x>l&&i>0&&pot[i-1].y<pot[i].x)
					{
						ff=1;
						printf("0\n");
						break;
					}
					else if(pot[i].x>l)
						break;
				}
				sort(pot+fi,pot+i,cmp1);
				num[++mcnt]=pot[i-1].x;
				num[++mcnt]=pot[i-1].y;
				l=pot[i-1].y;
				fi=i;
				if(ff)
					break;
			}
			if(ff)
			{
				puts("");
				continue;
			}
			printf("%d\n",mcnt/2);
			for(i=1;i<=mcnt;i+=2)
			{
				printf("%d %d\n",num[i],num[i+1]);
			}
		}
		else
		{
			printf("0\n");
		}
		if(t)
			puts("");
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/84660920
今日推荐