贪心策略是每次向后寻找能跳到的区间里面右端最远的那一个,如果挑不到或者最后不足N那么就证明无法满足。
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005; struct Node{ int l; int r; } node[MAXN]; bool comp(Node n1, Node n2) { if (n1.l==n2.l) return n1.r>n2.r; return n1.l<n2.l; } int main() { int N, M; scanf("%d%d", &N, &M); for (int i=0;i<M;i++) { scanf("%d", &node[i].l); scanf("%d", &node[i].r); } sort(node, node+M,comp); if (node[0].l!=1) { printf("-1"); return 0; } int ans = 1, maxr = node[0].r, temp = node[0].r; for (int i=1;i<M&&maxr<N;) { while (node[i].l<=maxr+1&&i<M) { temp = max(temp, node[i].r); i++; } if (temp==maxr) { break; } ans++; maxr = temp; } if (maxr>=N) { printf("%d", ans); } else { printf("-1"); } return 0; }