此题就是给你一堆小区间,然后用尽量小的小区间数目填满大区间,输出最小值,如果填不满输出-1,。通常做法就是排序,再贪心最大的区间右边界。但是还有一种做法,是在Discuss里看见一个大神写的一段无排序的精简代码,想法也和贪心方式差不多,精妙之处就是拿了一整段空间来保存每个可用空间,然后用了一个“指针”now来标记当前状态,接着用pre和to去表示区间的起始和终止位置。然后依次循环判断即可。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
int s[1000050]= {0};
int main()
{
int n, m;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
{
int a, b;
scanf("%d%d",&a,&b);
s[a] = s[a] > b ? s[a] : b;
}
int to=0, now=1, pre=1, cont=0;
while(now<=m)
{
for(int i=pre; i<=now; i++)
if(to<s[i])
{
to=s[i];
pre=i;
}
if(now==to+1)
{
printf("-1\n");
return 0;
}
now=to+1;
cont++;
}
printf("%d\n",cont);
return 0;
}