当前位置: 首页 > news >正文

区间和并—acwing

题目一:区间和并

803. 区间合并 - AcWing题库

代码

PII存储区间,排序左端点。first存左端点。

遍历区间,考虑边界情况。每访问一个区间,都更新为最右边的那个端点(max)

是否合并区间通过,该区间,与上一个区间ed(最右边端点)比较。右边则,res++;

#include<bits/stdc++.h>
using namespace std;using PII = pair<int,int>;
int n;
const int N = 1e5+10;
PII a[N];int main() {cin >> n;for(int i = 0; i < n; i ++) {int l, r;cin >> l >> r;a[i] = {l,r};}int res = 0;sort(a,a+n);int ed = -2e9;for(int i = 0; i < n; i ++) {if(a[i].first>ed) {res ++;}ed = max(ed,a[i].second);}cout << res << endl;return 0;
}

代码2(模板)

// yxc 区间和并模板代码
#include<bits/stdc++.h>using namespace std;
using PII = pair<int,int>;const int N = 1e5+10;int n;
vector<PII> a;void solve(vector<PII> &a) {vector<PII> res;sort(a.begin(), a.end());// 区间边界初始值int st = -2e9, ed = -2e9;for(auto x : a) {if(ed<x.first) {// 开始的边界处理if(st != -2e9) res.push_back({st,ed});st = x.first, ed = x.second;}else ed = max(ed,x.second);}// 最后的区间 边界//防空if(st!=-2e9) res.push_back({st,ed});a = res;
}int main() {cin >> n;for(int i = 0; i <= n; i ++) {int l, r;cin >> l >> r;a.push_back({l,r});}solve(a);cout << a.size() << endl;return 0;
}


http://www.mrgr.cn/news/80195.html

相关文章:

  • backtesting.py介绍和相关资料
  • 29.在Vue 3中使用OpenLayers读取WKB数据并显示图形
  • 学习笔记069——Java集合框架
  • 理解数据结构 hashtable的简易理解思路
  • 米哈游前端面试题及参考答案
  • [OpenGL] Transform feedback 介绍以及使用示例
  • More Effective C++之操作符operators
  • gpu硬件架构
  • 《拉依达的嵌入式\驱动面试宝典》—前言目录篇
  • 操作系统内存管理
  • c语言数据结构与算法--简单实现线性表(顺序表+链表)的插入与删除
  • Leetcode二叉树部分笔记
  • 单片机最小系统
  • Vue 组件化开发:构建高质量应用的核心
  • CA证书的核心解读:它是什么,以及如何发挥作用
  • Towards Frame Rate Agnostic Multi-object Tracking—迈向帧率无关的多目标跟踪
  • Python粉色圣诞树
  • 网格算法(Grid Algorithm)及其Python实现
  • 公钥基础设施(PKI)全面解析
  • 【WRF安装】WRF编译错误总结1:HDF5库包安装