A21 排序 区间合并

视频链接:52 排序 区间合并_哔哩哔哩_bilibili

 

 

Luogu P1496 火烧赤壁

复制代码
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

#define N 20005
struct line{    //线段
  int l,r;
  bool operator<(line &t){
    return l<t.l;
  }
}a[N];
int n,st,ed,sum;
//a[] 存储每条线段的起点,终点
//st  存储合并区间的起点
//ed  存储合并区间的终点
//sum 存储合并区间的长度

int main(){
  scanf("%d",&n);
  for(int i=1;i<=n;i++) 
    cin>>a[i].l>>a[i].r;
  sort(a+1,a+n+1); //按起点排序
  
  st=a[1].l; ed=a[1].r;
  sum+=a[1].r-a[1].l;
  for(int i=2; i<=n; i++){
    if(a[i].l<=ed){
      if(a[i].r<ed) //覆盖
        continue;
      else {        //重叠
        st=ed;
        ed=a[i].r;
        sum+=ed-st;
      }
    }
    else{           //相离
      st=a[i].l;
      ed=a[i].r;
      sum+=ed-st;
    }
  }
  cout<<sum<<endl;
  return 0;
}
复制代码

 

posted @   董晓  阅读(437)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示