题意:
区间覆盖问题,给你一些区间,让你用最少的区间数覆盖【0,M】,并输出所用区间。
思路:
跟上次写的UVA 10382 Watering Grass一个套路,上次写的应该是该题的变形题。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100005;
struct seg{
int l, r;
}a[N],ans[N];
int cmp(seg a,seg b) {
return a.l < b.l ;
}
int main() {
int cas;
scanf("%d", &cas);
while (cas--) {
memset(ans, 0, sizeof(ans));
memset(a, 0, sizeof(a));
int m;
scanf("%d", &m);
int left, right;
int n = 0;
while (~scanf("%d%d", &left, &right) ) {
if (!left&&!right)
break;
a[n].l = left;
a[n].r = right;
n++;
}
sort(a, a + n, cmp);
int cnt = 0, ok = 0, pos = n;
left = 0; right = 0;
if (a[0].l <= 0) {
int i = 0;
while (i < n) {
int j = i;
while (j < n&&a[j].l <= left) {
if (a[j].r > right) {
right = a[j].r;
pos = j;
}
j++;
}
if (j == i)
break;
i = j;
left = right;
cnt++;
ans[cnt] = a[pos];
if (right >= m) {
ok = 1;
break;
}
}
}
if (ok) {
printf("%d\n", cnt);
for (int i = 1; i <= cnt; i++)
printf("%d %d\n", ans[i].l, ans[i].r);
}
else
printf("0\n");
}
return 0;
}