原题链接:https://ac.nowcoder.com/acm/contest/392/A
排序后贪心即可, 每次 End = max{r[i]} (l[i] <= End + 1)
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 const int MAX_LEN = 1e5 + 5; 6 struct section 7 { 8 int l, r; 9 }a[MAX_LEN]; 10 int n, m; 11 bool cmp(section a, section b) { return a.l < b.l; } 12 int main() 13 { 14 ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); 15 cin >> n >> m; 16 for (int i = 1; i <= m; i++) 17 cin >> a[i].l >> a[i].r; 18 sort(a + 1, a + m + 1, cmp); 19 int end = 0, tot = 0, maxr = 0; 20 for (int i = 1; i <= m; i++) 21 if (a[i].l <= end + 1) 22 { 23 if (a[i].r > maxr) 24 maxr = a[i].r; 25 } 26 else 27 { 28 end = maxr; 29 maxr = 0; 30 tot++; 31 if (a[i].l <= end + 1) 32 { 33 if (a[i].r > maxr) 34 maxr = a[i].r; 35 } 36 } 37 if (end < n && maxr) 38 { 39 end = maxr; 40 tot++; 41 } 42 if (end < n) puts("-1"); 43 else cout << tot << endl; 44 45 return 0; 46 }