当前位置:网站首页>区间贪心(区间合并)
区间贪心(区间合并)
2022-08-04 17:28:00 【疯疯癫癫才自由】
803. 区间合并
给定 n
个区间 [li,ri]
,要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3]
和 [2,6] 可以合并为一个区间 [1,6]
。
输入格式
第一行包含整数 n
。
接下来 n
行,每行包含两个整数 l 和 r
。
输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。
数据范围
1≤n≤100000
,
−109≤li≤ri≤109
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
按左端点从小到大排序,再按右端点从小到大排序,每次比较前一区间的右端点和后一区间的左端点,如果有交集,则可以合并为一个新区间,否则不能合并为一个区间。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int,int> PLL;
void merge(vector<PLL> &vec) //合并区间
{
sort(vec.begin(),vec.end()); //默认按第一个元素从小到大排序,再按第二个元素排序
vector<PLL> res;
int st=vec[0].first,ed=vec[0].second;;
for(int i=1;i<vec.size();++i)
{
if(ed<vec[i].first)
{
res.push_back({st,ed});
st=vec[i].first,ed=vec[i].second;
}
else
ed=max(ed,vec[i].second);
}
res.push_back({st,ed}); //最后一个坐标区间加上去
vec=res;
}
int main()
{
int n;
cin >> n;
vector<PLL> vec;
for(int i=0;i<n;++i)
{
int l,r;
cin >> l >> r;
vec.push_back({l,r});
}
merge(vec);
cout << vec.size() << endl;
return 0;
}
边栏推荐
- The second step through MySQL in four steps: MySQL index learning
- 如何模拟后台API调用场景,很细!
- el-date-picker 设置时间范围
- Digital-intelligent supply chain management system for chemical manufacturing industry: build a smart supply system and empower enterprises to improve production efficiency
- 树莓派通过API向企业微信推送图文
- LeetCode Question of the Day - 1403. Minimum Subsequence in Non-Increasing Order
- 我的大一.
- 图扑软件与华为云共同构建新型智慧工厂
- 一张图片怎么旋转90度。利用ps
- 微信jsApi调用失效的相关问题
猜你喜欢
随机推荐
为什么买域名必须实名认证?这样做什么原因?
C. LIS or Reverse LIS?
C# Sqlite database construction and use skills
我的大一.
树莓派连接蓝牙音箱
罗振宇折戟创业板/ B站回应HR称用户是Loser/ 腾讯罗技年内合推云游戏掌机...今日更多新鲜事在此...
华为云计算HCIE之oceanstor仿真器的安装教程
JSP的Web监听器(Listener)
SRM供应商协同管理系统功能介绍
动态数组底层是如何实现的
对象实例化之后一定会存放在堆内存中?
荣耀互联对外开放,赋能智能硬件合作伙伴,促进全场景生态产品融合
SQL优化最全总结 - MySQL(2022最新版)
机器学习(十一):KNN(K近邻)
CAS:474922-26-4,DSPE-PEG-NH2,DSPE-PEG-amine,磷脂-聚乙二醇-氨基供应
shell函数内如何调用另一个函数
域名哪家便宜?怎么买便宜域名?
【LeetCode Daily Question】——374. Guess the size of the number
php如何查询字符串以什么开头
从云计算到函数计算









