题目链接:http://poj.org/problem?id=2376
大体思路:
首先对每个区间按照左端点进行升序排序,之后再进行区间的覆盖。在覆盖的过程中我们从还没有选择过的奶牛中选择与当前区间有交集且右端点最大的奶牛来进行更新。最后再特判是否有解即可。
code:
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5;
struct cow {
int l, r;
} c[N];
int n, t, ans;
bool cmp(cow a, cow b) {
return a.l<b.l;
}
int main() {
cin >> n >> t;
for (int i=1; i<=n; i++)
cin >> c[i].l >> c[i].r;
sort(c+1, c+n+1, cmp);
int max=0, now=1;//max这里表示已经开拓的区间
while (max<t) {
int min=max+1;//min表示将要进行区间覆盖的左边界
for (int i=now; i<=n; i++) {//i=now每次从还没有选择过的奶牛中选择区间
if (c[i].l<=min && c[i].r>=min) max=max>c[i].r?max:c[i].r;//max记录最大区间右边界,作为已经覆盖的区间
else if (c[i].l>min) {//这里表示当min作为左边界时已经没有区间覆盖了
now=i;//记录这个区间,因为这个应该是下一个min选择的,所以下一次还是要从它开始选择
break;
}
}
if (max<min) break;//若是不再发生覆盖
else ans++;
}
if (max>=t) cout << ans;
else cout <<"-1";
return 0;
}