1. 程式人生 > >UVA - 10020 Minimal coverage (區間更新,貪心)

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;
 }