版权声明:请大家斧正,如喜欢的话,为拙见点一个赞吧。 https://blog.csdn.net/qq_39897867/article/details/82734006
#题目
https://www.luogu.org/problemnew/show/P1496
#结题思路
将所有的这些区间排一个序,这样就可以得到一个可能会相互覆盖(/重合)的区间,然后从从左到右枚举即可。
#代码
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{int x,y;}a[21100];
int n,begin,end,sum;
bool cmp(node x,node y){return x.x<y.x; }
int main()
{
scanf("%d",&n);
for (register int i=1;i<=n;i++) scanf("%d%d",&a[i].x,&a[i].y);
sort(a+1,a+n+1,cmp);
begin=a[1].x; end=a[1].y; sum=a[1].y-a[1].x;
for (register int i=2;i<=n;i++)
if (a[i].x<=end&&a[i].y>=end)
{ begin=end; end=a[i].y; sum+=end-begin;}
else if (a[i].x>end)
{ begin=a[i].x; end=a[i].y; sum+=end-begin; }
printf("%d",sum);
}