区间合并

风格不统一 提交于 2020-01-22 10:02:49

题目链接:https://www.acwing.com/problem/content
题意:给定 n 个区间 [li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3]和[2,6]可以合并为一个区间[1,6]。
数据范围
1≤n≤100000,
−109≤li≤ri≤109
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
思维:其实还是有点像贪心的思维啊。我们把所有的区间按照左端点由小到大排序,有重叠的就不断更新右端点,直到形成一个独立区间后存入答案res中,再把左端点更新为下一个独立起点……如此下去res的size就是最总答案啦!!
代码实现:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5+5;
int n;
void merge(vector<PII> &s)
{
    vector<PII> res;
    sort(s.begin(),s.end());
    int st = -INF, ed = -INF;
    for(vector<PII>::iterator it = s.begin(); it != s.end(); it ++ )
        if(ed < it -> first){
            if(st != -INF)
               res.push_back({st,ed});
            st = it -> first, ed = it -> second;
        }
        else ed = max(ed, it -> second);
    if(st != -INF) res.push_back({st,ed});
    s = res;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin >> n;
    vector<PII> s;
    for(int i = 1; i <= n; i ++ ){
        int l, r;
        cin >>l >> r;
        s.push_back({l,r});
    }
    merge(s);
    cout << s.size() << endl;
    return 0;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!