用贪心解决的区间问题
《区间选点》
即一个点尽量在更多的区间上,但我们不妨从另一个方面想:在一个区间上的点,始终不能够与另一个区间有关系的情况是什么?
1 #include <iostream>
2 #include <cstring>
3 #include <algorithm>
4 using namespace std;
5 const int N = 1e5 + 10;
6 struct Section
7 {
8 int l, r;
9 } arr[N];
10 int main()
11 {
12 int n;
13 cin >> n;
14 for (int i = 1; i <= n; i++)
15 cin >> arr[i].l >> arr[i].r;
16 sort(arr+1,arr+n+1,[](Section a,Section b){
17 return a.r<b.r;
18 });
19 int maxr=-2e9,ans=0;
20 for (int i=1;i<=n;i++)
21 {
22 if (maxr<arr[i].l)
23 {
24 ans++;
25 maxr=arr[i].r;
26 }
27 }
28 cout<<ans;
29 return 0;
30 }
《最大不相交区间数》
即,选择出区间与区间之间互不相交的最大区间个数
所以代码也与上面相同
《区间分组》

1 #include <iostream>
2 #include <cstring>
3 #include <algorithm>
4 #include <queue>
5 using namespace std;
6 const int N = 1e5 + 10;
7 int n;
8
9 struct Section
10 {
11 int l, r;
12 } arr[N];
13
14 int main()
15 {
16 int n;
17 cin >> n;
18 for (int i = 1; i <= n; i++)
19 cin >> arr[i].l >> arr[i].r;
20 sort(arr + 1, arr + n + 1, [](Section a, Section b)
21 { return a.l < b.l; });
22 priority_queue<int, vector<int>, greater<int>> q;
23 q.push(arr[1].r);
24 for (int i = 2; i <= n; i++)
25 {
26 int t = q.top();
27 if (arr[i].l > t)
28 q.pop();
29 q.push(arr[i].r);
30 }
31 cout<<q.size();
32 return 0;
33 }
《区间覆盖》
1 #include <iostream>
2 #include <algorithm>
3 #include <cstring>
4 using namespace std;
5 const int N = 1e5 + 10;
6 int s, t, n;
7 struct Section
8 {
9 int l, r;
10 } arr[N];
11 int main()
12 {
13 cin >> s >> t >> n;
14 for (int i = 1; i <= n; i++)
15 cin >> arr[i].l >> arr[i].r;
16 sort(arr + 1, arr + n + 1, [](Section x, Section y)
17 { return x.l < y.l; });
18 int ans = 0;
19 bool flag = false;
20 for (int i = 1; i <= n; i++)
21 {
22 int maxr = -2e9, j = i;
23 if (arr[i].l > s)
24 break;
25 while (j <= n && arr[j].l <= s)
26 {
27 maxr = max(maxr, arr[j].r);
28 j++;
29 }
30 ans++;
31 s = maxr;
32 i = j - 1;
33 if (s >= t)//这个if判断语句还是挺有讲究的,因为flag在这里改变
34 {
35 flag = true;
36 break;
37 }
38 }
39 if (flag)
40 cout << ans;
41 else
42 cout << -1;
43 return 0;
44 }