音无结弦之时,天使跃动之心。立于浮华之世,奏响天籁之音。.|

次林梦叶

园龄:3年3个月粉丝:21关注:2

用贪心解决的区间问题

《区间选点》

 

 即一个点尽量在更多的区间上,但我们不妨从另一个方面想:在一个区间上的点,始终不能够与另一个区间有关系的情况是什么?

复制代码
 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 }
复制代码

 

本文作者:次林梦叶

本文链接:https://www.cnblogs.com/cilinmengye/p/16542166.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   次林梦叶  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起