https://www.rqnoj.cn/problem/13
m段区间求区间并长度
题目描述
某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米。我们可以把马路看成一个数轴,马路的一端在数轴0的位置,另一端在L的位置;数轴上的每个整数点,即0,1,2,……,L,都种有一棵树。
由于马路上有一些区域要用来建地铁。这些区域用它们在数轴上的起始点和终止点表示。 已知任一区域的起始点和终止点的坐标都是整数,区域之间可能有重合的部分。现在要把这些区域中的树(包括区域端点处的两棵树)移走。你的任务是计算将这些树都移走后,马路上还有多少棵树。
输入格式
输入的第一行有两个整数:L(1 <= L <= 10000)和 M(1 <= M <= 100),L代表马路的长度,M代表区域的数目,L和M之间用一个空格隔开。接下来的M行每行包含两个不同的整数,用一个空格隔开,表示一个区域的起始点和终止点的坐标。
输出格式
输出包括一行,这一行只包含一个整数,表示马路上剩余的树的数目。
/* ***********************************************
Author :Lu_cky
Created Time :2016年05月31日 星期二 10时12分33秒
File Name :main.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define LL long long
using namespace std;
const int SIZE=1e2+10;
const int maxn=1<<30;
struct line{
int l;
int r;
bool operator<(const line &other)const{
return l<other.l;
}
}li[SIZE];
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int L,m;
while(scanf("%d%d",&L,&m)!=EOF){
for(int i=0;i<m;i++)
scanf("%d%d",&li[i].l,&li[i].r);
sort(li,li+m);
int ans=0;
int l=li[0].l,r=li[0].r;
for(int i=1;i<m;i++){
if(li[i].l<=r){
r=max(r,li[i].r);
}
else {
ans+=r-l+1;
l=li[i].l;
r=li[i].r;
}
}
ans+=r-l+1;
printf("%d\n",L+1-ans);
}
return 0;
}