贪心策略:从左往右选择,选择区间长的。
- 按时间起点排序,每次更新起点begin = end + 1;
- 选择剩下区间中可覆盖begin的最远end。
#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const ll mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps = 1e-10;
const ll inf = 1e7;
const ll maxn = 25000 + 5;
inline ll read() {
ll s = 0, w = 1;
char ch = getchar();
for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1;
for (; isdigit(ch); ch = getchar()) s = (s << 1) + (s << 3) + (ch ^ 48);
return s * w;
}
inline void write(ll x) {
if (!x) {
putchar('0');
return;
}
char F[40];
ll tmp = x > 0 ? x : -x;
if (x < 0)putchar('-');
int cnt = 0;
while (tmp > 0) {
F[cnt++] = tmp % 10 + '0';
tmp /= 10;
}
while (cnt > 0)putchar(F[--cnt]);
}
inline ll gcd(ll x, ll y) {
return y ? gcd(y, x % y) : x;
}
ll qpow(ll a, ll b) {
ll ans = 1;
while (b) {
if (b & 1) ans *= a;
b >>= 1;
a *= a;
}
return ans;
}
ll qpow(ll a, ll b, ll mod) {
ll ans = 1;
while (b) {
if (b & 1)(ans *= a) %= mod;
b >>= 1;
(a *= a) %= mod;
}
return ans % mod;
}
inline int lowbit(int x) {
return x & (-x);
}
// 贪心策略:从左往右选择,选择区间长的
// 按时间起点排序,更新begin = end + 1
// 选择剩下区间中可覆盖区间的最远end
struct node
{
int s, e;
}c[maxn];
bool cmp(node a, node b)
{
return a.s < b.s;
}
int main()
{
int n, t;
scanf("%d %d", &n, &t);
for(int i = 0; i < n; i++)
{
scanf("%d %d", &c[i].s, &c[i].e);
}
sort(c, c+n, cmp);
int over = 0;
int pos = 0;
int sum = 0;
while(over < t)
{
int start = over + 1;
for(int i = pos; i < n; i++)
{
if(c[i].s <= start)
{
if(c[i].e > over)
over = max(over, c[i].e);
}
else
{
pos = i;
break;
}
}
if(start > over)
{
cout << "-1" << endl;
return 0;
}
else
{
sum++;
}
if(over >= t)
{
cout << sum << endl;
}
}
return 0;
}