UVA10020(贪心--最小覆盖问题)

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

题解:按右端点从大到小排序后,然后每次选最大又区间且左区间小于等于当前右区间的,逐渐扩大右区间直到大于等于所求的右区间即可。将选定的线段存入另一个数组,再根据左端点从小到大排序好输出。

ac代码

#include<iostream>       
#include<cstdlib>      
#include<cstdio> 
#include<cstring>      
#include<cmath>           
#include<string>      
#include<cstdlib>      
#include<iomanip>      
#include<vector>      
#include<list>      
#include<map>      
#include<queue>    
#include<algorithm>
using namespace std;
const int N = 100005;
struct node
{
	int x, y;
}p[N];
bool cmp(node s1, node s2)
{
	return s1.y > s2.y;
}
bool cmp1(node s1, node s2)
{
	return s1.x < s2.x;
}
int main()
{
	int n, m, i, a, b, v, g;
	cin >> n;
	while (n--)
	{

		cin >> m;
		node q[5005];
		int k = 0;
		v = 0;
		for (i = 0;; i++)
		{
			scanf("%d%d", &a, &b); if (a == 0 && b == 0)break;
			else {
				p[i].x = a;
				p[i].y = b;
			}
		}
		sort(p, p + i, cmp);
		while (k < m)
		{
			g = k;
			for (int j = 0; p[j].y > k&&j < i;)
			{
				if (p[j].x <= k)
				{

					g = p[j].y;
					q[v].x = p[j].x;
					q[v].y = p[j].y;
					v++; break;//因为已经从大到小排序好了,所以就一找到左区间是满足大于等于当前右区间的,该线段的右端点即是满足条件的最大端点,
				}j++;
			}
			if (k == g) {
				v = 0; break;
			}//说明g没有改变,即说明没有办法更新右区间了,结束。
			k = g;

		}
		cout << v << endl;
		sort(q, q + v, cmp1);
		for (int j = 0; j < v; j++)
			printf("%d %d\n", q[j].x, q[j].y);
		if (n)printf("\n");
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43965698/article/details/87859015
今日推荐