UVA - 10020 Minimal coverage (区间更新,贪心)

 Minimal coverage 
The Problem
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].

The 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.

The 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,和一些区间[Li,Ri]。。要选出几个区间能完全覆盖住[0,M]区间。要求数量最少。。如果不能覆盖输出0.

思路:把区间记为【xi,yi】;那么思考,只要按照xi从小到达排序,如果第一个区间起点不包含0就是无解的,否则则选择包含起点的最长区间,选择完后,新的起点就是yi了,在选择下一段区间......

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
	int st,end;
}edge[100005];
int a[100005],b[100005];
int n,M;
bool cmp(const node a,const node b)
{
	return a.st<b.st;
}
int solve()
{
	int i;
	int l=0,cnt=0,maxx=0;
	if(edge[0].st>0) return 0; //如果最小的左端点都不能包含0 
while(1)
{
	if(l>=M) break;
	for(i=0;i<=n;i++)
	{
		if(edge[i].st<=l&&edge[i].end>l)
		{
			//maxx=max(edge[i].end,maxx);
			if(edge[i].end>maxx)
			{
				maxx=edge[i].end;
				a[cnt]=edge[i].st;
				b[cnt]=edge[i].end;
			}
		}
 	}
 	if(maxx<=l) return 0;
 		
 	l=maxx;
 	cnt++;
}
return cnt;
}
int main()
{
	int t,i;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&M);
		n=0;
		while(1)
		{
			scanf("%d%d",&edge[n].st,&edge[n].end);
			if(edge[n].st==0&&edge[n].end==0) 
			{
				n--;
				break;
			 } 
			n++;
		}
		sort(edge,edge+n+1,cmp);
		int count=solve();
		cout<<count<<endl;
		for(i=0;i<count;i++)
		printf("%d %d\n",a[i],b[i]);
	}
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/zvenWang/article/details/84582174