区间合并的方法
1.需要一个结构体,两个变量说明左右端点;
2/因为题目的左右端点输入不是固定的有可能大的在前小的在后,所以需要给输入的端点进行交换,始终保持小的在前大的在后;
3/要想使用区间合并的方法必须要是结构体的中的元素是保持升序的,不然结构体的元素乱跳会导致错误,所以就按照左端的大小进行升序排序,sort函数;
4/ 定义ll, rr变量分别代表左右端点,比较rr变量和下一个区间左端的大小,如果rr大于等于(注意:一定是大于等于)下一个区间左端点的就让下一个区间的右端点和当前区间的rr比较大小,找最大的当rr,因为有可能是包含的情况; 如果不是不符合就减掉上一个区间,使当前区间的左右端点分别当新的左右端点; 5/最后会有一个区间没有剪掉,记得最后一个的减法;
6/c++ 中有max 和 min 函数,对结构体的元素进行排序的时候需要自定义一个函数来判断大小
7/使用malloc 函数记得释放内存吧
#include<iostream>
#include<vector>
#include<cstdio>
#include<cmath>
#include<stdlib.h>
#include<algorithm>
using namespace std;
struct ty{
int x;
int y;
};
bool comp(ty a,ty b)
{
if(a.x<b.x) return 1;
return 0;
}
int main()
{
int l,n;
int count=0;
scanf("%d%d",&l,&n);
struct ty *a=(struct ty*)malloc((n+1)*sizeof(struct ty));
count=l+1;
for(int i=1;i<=n;i++)
{
cin>>a[i].x>>a[i].y;
if(a[i].x>a[i].y) swap(a[i].x,a[i].y);
}
sort(a+1,a+1+n,comp);
int ll,rr;
ll=a[1].x,rr=a[1].y;
for(int i=2;i<=n;i++)
{
if(rr>=a[i].x)
{
rr=max(a[i].y,rr);
}
else
{
count-=(rr-ll+1);
ll=a[i].x;
rr=a[i].y;
}
}
count-=(rr-ll+1);
cout<<count;
free(a);
return 0;
}



京公网安备 11010502036488号