UVA 10020 Minimal coverage

http://uva.onlinejudge.org/external/100/10020.pdf


给定n条线段,问最少用几条可以覆盖0到M。按左端排序,每次选最长的(贪心)


#include<stdio.h>
#include<iostream>  
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 50005;
int i, t, m, l, r, a[maxn], sum, f[maxn], en, ff, ll, q, u;
struct rz
{
	int l, r;
}; rz b[maxn], c[maxn];

int main(){
	cin >> t;
	while (t--)
	{
		cin >> m;
		memset(a, -1, sizeof(a));
		while (~scanf("%d%d", &l, &r), l || r)
		{
			if (r < 0) continue;
			if (l < 0) ll = 0; else ll = l;
			if (a[ll] < r) 
			{ 
				a[ll] = r;
				b[ll].l = l; b[ll].r = r;
			}	
		}
		c[0].l = b[0].l;
		c[0].r = b[0].r;
		q = 0; en = a[0]; ff = 1; u = 0;
		while (en < m&&q <= en)
		{	
			for (u = i = q; i <= en; i++)
				if (a[i]>a[u]) u = i;
			q = en + 1; en = a[u];
			c[ff].l = b[u].l;
			c[ff++].r = b[u].r;
		}
		if (en >= m) {
			printf("%d\n", ff);
		for (i = 0; i < ff; i++) printf("%d %d\n", c[i].l, c[i].r);
		}
		else printf("0\n");
		if (t) printf("\n");
	}
	return 0;
}


你可能感兴趣的:(uva,贪心)