POJ 2376
题意:
给出一给大区间和n各小区间,问最少可以用多少小区间覆盖整个大区间。
分析:
贪心法。设t为当前所有已确定区间的最右端,那我们可以每次都取所有可选的小区间(左端点<=t+1)中右端点最大的值,然后更新最右端点ans++。初始时t=0
注:所谓衔接不是[0,1][1,2]这样首尾相接,而是[0,1][2,3]即可,故为 t+1
#include<iostream> #include<algorithm> #include<string.h> #include<cstring> #include<vector> #include<set> #include<stdio.h> #include<stack> #include<bitset> using namespace std;int n,T; struct P {int x,y; }s[25002]; int cmp(P a,P b) {return a.x<b.x; } int main() {scanf("%d%d",&n,&T);for(int i=0;i<n;i++)scanf("%d%d",&s[i].x,&s[i].y);sort(s,s+n,cmp);s[n].x=0x7fffffff; //边界处要考虑int t=0,temp=0,ans=0;bool f=0;for(int i=0;i<n;i++){if(s[i].x<=t+1){if(s[i].y>temp)temp=s[i].y,f=1;if(s[i+1].x>t+1&&f){ans++;t=temp;f=0;}}}if (t<T) printf("-1\n"); else printf("%d\n",ans);return 0; }