区间贪心,用最少的线段覆盖的问题,首先要知道求解的过程中区间可能连不上,这就会输出-1,然后就是要想明白什么时候要退出循环,
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
const int maxn = 25005;
bool cmp(pa a, pa b) {
if (a.fi != b.fi) return a.fi < b.fi;
else return a.se > b.se;
}
int main() {
int n, t;
cin >> n >> t;
int cnt = 0;
pa p[maxn];
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
if (y < 1) continue;
if (x > t) continue;
if (y > t) y = t;
if (x < 1) x = 1;
p[cnt++] = make_pair(x, y);
}
sort(p, p + cnt, cmp);
if (p[0].fi > 1) cout << -1;
else {
int last = p[0].se;
int ans = 1;
int index = 1;
while (true) {
int pos = index;
int tmp_max = last;
while (pos < cnt && p[pos].fi <= last + 1) {
if (p[pos].se > tmp_max) {
tmp_max = p[pos].se;
}
pos++;
}
if (tmp_max > last) {
ans++;
index = pos;
last = tmp_max;
} else break;
}
if (last == t) cout << ans;
else cout << -1;
}
return 0;
}