• 区间合并(AcWing.803 )


    #include<iostream>
    #include<vector>
    #include<algorithm>
    
    using namespace std;
    
    typedef pair<int, int> PII;
    
    int n;
    
    void merge(vector<PII> &interval)
    {
        vector<PII> ans;
    
        sort(interval.begin(), interval.end()); //! pair排序 优先左端点, 再以右端点排序
    
        int st = -1e9-10, ed = -1e9-10;  //! 只要比 -1e9 小就可以
        for(auto item:interval)
        {
            if(ed<item.first) //! 第一段区间一定是  ed< item.first
            {
                if(st!=-1e9-10) ans.push_back({st,ed}); //! 第一次在这里初始化
                st = item.first, ed = item.second;//! 第一段区间从这里开始
            }
            else ed = max(ed, item.second);
        }//todo 这个循环结束之后还会剩下一个区间
        if(st!=-1e9-10) ans.push_back({st,ed});  //! 如果不是空的  那我们就加上一段
    
        interval = ans;
    }
    
    int main(void)
    {
        ios::sync_with_stdio(false);
        cin >> n;
    
        vector<PII> interval;
        while(n--)
        {
            int l, r;
            cin >> l >> r;
      
        interval.push_back({l, r});
        }
    
        merge(interval);
    
        cout << interval.size() << endl;
    
        return 0;
    }

    介绍一种结构体合并区间的算法。

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    
    using namespace std;
    
    const int N = 100010;
    struct node{
        int start;
        int end;
    }a[N];
    int n;
    
    bool cmp(node c,node d){//结构体排序,保证左区间从小到大排序
        return c.start < d.start;
    }
    
    int main(){
        scanf("%d",&n);
        for(int i = 0; i < n; i++) scanf("%d%d",&a[i].start,&a[i].end);
        sort(a,a+n,cmp);
        //for(int i = 0; i < n; i++) cout << a[i].start << ' ' << a[i].end << endl;
        int s = a[0].start,e = a[0].end;
        int ans = 1;//必定有一个区间
        for(int i = 1; i < n; i++){
            if(a[i].start <= e && a[i].end > e) e = a[i].end;//两种情况,有交集
            else if(a[i].start > e) s = a[i].start,e = a[i].end,ans++;//无交集
        }
        cout << ans << endl;
        return 0;
    }
  • 相关阅读:
    【tensorflow】神经网络的一些基本概念(前向传播、反向传播、损失函数、梯度下降法、学习率)和设计过程
    【opencv+python】图像的基本操作:缩放、剪切、位移、旋转、仿射变换
    【tensorflow】利用神经网络绘制股票价格拟合曲线
    Tuple
    2020-08-17T15:35:54.525+08:00
    FTP协议协议
    centos7常规系统指标监控shell脚本
    AWK传入shell变量举例
    洛谷-P5143 攀爬者
    洛谷-P1104 生日
  • 原文地址:https://www.cnblogs.com/zyz010206/p/12348332.html
Copyright © 2020-2023  润新知