// Problem: CF1132C Painting the Fence
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF1132C
// Memory Limit: 250 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
struct wall{
int l,r;
}w[5001];
int cnt[5001];
struct Cf{
int num,pnt;
}cf[5001];
bool cmp(Cf a,Cf b){
return a.num<b.num;
}
int main(){
memset(cnt,0,sizeof(cnt));
int n,q;
cin>>n>>q;
for(int i=1;i<=q;i++){
cin>>w[i].l>>w[i].r;
for(int j=w[i].l;j<=w[i].r;j++){
cnt[j]++;
}
}
for(int i=1;i<=q;i++){
cf[i].pnt=i;
for(int j=w[i].l;j<=w[i].r;j++){
if(cnt[j]>=1) cf[i].num++;
}
}
sort(cf+1,cf+q+1,cmp);
for(int i=1;i<=2;i++){
for(int j=w[cf[i].pnt].l;j<=w[cf[i].pnt].r;j++){
cnt[j]--;
}
// cout<<cf[i].num<<" ";
}
// cout<<"\n";
int ans=0;
for(int i=1;i<=n;i++){
if(cnt[i]) ans++;
}
cout<<ans;
return 0;
}
my output
1784
std's output
1785