#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool cmp(pair<int,int> a,pair<int,int> b){
	if(a.first!=b.first)
		return a.first<b.first;
	else
		return a.second<b.second;
}
/*int arr[100100];
int num1l[100100];
int num1r[100100];
int num2l[100100];
int num2r[100100];
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		scanf("%d",&arr[i]);
		if(arr[i]==1){
			num1l[i]=num1r[i]=1;
		}
		else if(arr[i]==2){
			num2l[i]=num2r[i]=1;
		}
	}
	for(int i=1;i<n;i++){
		if(num1l[i]!=0)
			num1l[i]+=num1l[i-1];
		if(num21[i]!=0)
			num2l[i]+=num2l[i-1];
	}
	for(int i=n-1;i>=0;i--){
		if(num1[i]!=0)
			num1l[i]+=num1l[i-1];
		if(num21[i]!=0)
			num2l[i]+=num2l[i-1];
	}
}*/
pair<int,int> pi[5010];
int arr[5010],tot[5010];
int num1[5010],num2[5010];
priority_queue<int,vector<int>,greater<int> >qq;
int main()
{
	int n,q;
	cin>>n>>q;
	for(int i=0;i<q;i++){
		scanf("%d%d",&pi[i].first,&pi[i].second);
	}
	sort(pi,pi+q,cmp);
//	cout<<"123";
	for(int i=0,j=0;i<=5000;i++){
		while(pi[j].first==i&&j<q){
			qq.push(pi[j].second);
			j++;
		}
		while(!qq.empty()&&qq.top()<i){
			qq.pop();
		}
		tot[i]=qq.size();
	}
	if(tot[0]==1)
		num1[0]=1;
	else if(tot[0]==2)
		num2[0]=1;
	for(int i=1;i<=5000;i++){
		if(tot[i]==1){
			num1[i]=num1[i-1]+1;
			num2[i]=num2[i-1];
		}
		else if(tot[i]==2){
			num1[i]=num1[i-1];
			num2[i]=num2[i-1]+1;
		}
		else{
			num1[i]=num1[i-1];
			num2[i]=num2[i-1];
		}
	}
	int ans=0;
	ans+=pi[0].second-pi[0].first+1;
	int mn=1000000000;
	int mx=pi[0].second;
	for(int i=1;i<q;i++){
		ans+=max(0,pi[i].second-max((pi[i].first-1),mx));
		mx=max(mx,pi[i].second);
	}
//	arr[0]=max(0,min(pi[1].first,pi[0].second+1)-pi[0].first);
//	for(int i=1;i<q-1;i++){
//		arr[i]=max(0,min(pi[i+1].first,pi[i].second+1)-max(pi[i].first,pi[i-1].second+1));
//	}
//	arr[q-1]=max(0,pi[q-1].second-max(pi[q-1].first-1,pi[q-2].second));
	for(int i=0;i<q;i++){
		for(int j=i+1;j<q;j++){
			if(pi[i].second<pi[j].first)
//				mn=max(0,min(mn,getans(pi[i].first,pi[i].second,0,1)+getans(pi[j].first,pi[j].second,0,1)));
				mn=min(mn,num1[pi[i].second]-num1[pi[i].first-1]+num1[pi[j].second]-num1[pi[j].first-1]);
			else{
//				mn=max(0,min(mn,getans(pi[i].first,pi[j].first-1,0,1)+getans(pi[i].second+1,pi[j].second,0,1)+getans(pi[j].first,pi[i].second,0,2)));
				mn=min(mn,num1[pi[j].first-1]-num1[pi[i].first-1]+num1[pi[j].second]-num1[pi[i].second]+num2[pi[i].second]-num2[pi[j].first-1]);

			}
		}
	}
	cout<<ans-mn<<endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
pair<int,int> pi[5010];
int arr[5010];
bool cmp(pair<int,int> a,pair<int,int> b){
	if(a.first!=b.first)
		return a.first<b.first;
	else
		return a.second<b.second;
}
int main()
{
	int n,q;
	cin>>n>>q;
	for(int i=0;i<q;i++){
		scanf("%d%d",&pi[i].first,&pi[i].second);
	}
	sort(pi,pi+q,cmp);
	int num=0;
	int ans=0;
	ans+=pi[0].second-pi[0].first+1;
	int mn=1000000000;
	for(int i=1;i<n;i++){
		ans+=max(0,pi[i].second-max((pi[i].first-1),pi[i-1].second));
	}
	arr[0]=min(pi[1].first,pi[0].second+1)-pi[0].first;
	for(int i=1;i<q-1;i++){
		arr[i]=min(pi[i+1].first,pi[i].second+1)-max(pi[i].first,pi[i-1].second+1);
	}
	arr[q-1]=pi[q-1].second-max(pi[q-1].first-1,pi[q-2].second);
	for(int i=0;i<q;i++){
		for(int j=0;j<q;j++){
//			if(j-i!=1)
//				mn=min(mn,arr[i]+arr[j]);
//			else{
				mn=max(0,min(mn,arr[i]+arr[j]+max(0,pi[i].second-pi[j].first+1)));
//			}
		}
	}
//	sort(arr,arr+q-1);
//	ans-=max(0,arr[0]);
//	ans-=max(0,arr[1]);
//	for(int i=0;i<q;i++)
//		cout<<arr[i]<<" ";
	cout<<ans-mn<<endl;
//	for(int i=0;i<q;i++)
//		cout<<pi[i].first<<" "<<pi[i].second<<endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
pair<int,int> pi[5010];
int arr[5010];
bool cmp(pair<int,int> a,pair<int,int> b){
	if(a.first!=b.first)
		return a.first<b.first;
	else
		return a.second<b.second;
}
int main()
{
	int n,q;
	cin>>n>>q;
	for(int i=0;i<q;i++){
		scanf("%d%d",&pi[i].first,&pi[i].second);
	}
	sort(pi,pi+q,cmp);
	int num=0;
	int ans=0;
	ans+=pi[0].second-pi[0].first+1;
	int mn=1000000000;
	for(int i=1;i<n;i++){
		ans+=max(0,pi[i].second-max((pi[i].first-1),pi[i-1].second));
	}
	arr[0]=min(pi[1].first,pi[0].second+1)-pi[0].first;
	for(int i=1;i<q-1;i++){
		arr[i]=min(pi[i+1].first,pi[i].second+1)-max(pi[i].first,pi[i-1].second+1);
	}
	arr[q-1]=pi[q-1].second-max(pi[q-1].first-1,pi[q-2].second);
	for(int i=0;i<q;i++){
		for(int j=0;j<q;j++){
//			if(j-i!=1)
//				mn=min(mn,arr[i]+arr[j]);
//			else{
				mn=min(mn,arr[i]+arr[j]+max(0,pi[i].second-pi[j].first+1));
//			}
		}
	}
//	sort(arr,arr+q-1);
//	ans-=max(0,arr[0]);
//	ans-=max(0,arr[1]);
//	for(int i=0;i<q;i++)
//		cout<<arr[i]<<" ";
	cout<<ans-mn<<endl;
//	for(int i=0;i<q;i++)
//		cout<<pi[i].first<<" "<<pi[i].second<<endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
pair<int,int> pi[5010];
int arr[5010];
bool cmp(pair<int,int> a,pair<int,int> b){
	if(a.first!=b.first)
		return a.first<b.first;
	else
		return a.second<b.second;
}
int main()
{
	int n,q;
	cin>>n>>q;
	for(int i=0;i<q;i++){
		scanf("%d%d",&pi[i].first,&pi[i].second);
	}
	sort(pi,pi+q,cmp);
	int num=0;
	int ans=0;
	ans+=pi[0].second-pi[0].first+1;
	int mn=1000000000;
	int mx=pi[0].second;
	for(int i=1;i<q;i++){
		ans+=max(0,pi[i].second-max((pi[i].first-1),mx));
		mx=max(mx,pi[i].second);
	}
	arr[0]=min(pi[1].first,pi[0].second+1)-pi[0].first;
	for(int i=1;i<q-1;i++){
		arr[i]=min(pi[i+1].first,pi[i].second+1)-max(pi[i].first,pi[i-1].second+1);
	}
	arr[q-1]=pi[q-1].second-max(pi[q-1].first-1,pi[q-2].second);
	for(int i=0;i<q;i++){
		for(int j=0;j<q;j++){
//			if(j-i!=1)
//				mn=min(mn,arr[i]+arr[j]);
//			else{
				mn=max(0,min(mn,arr[i]+arr[j]+max(0,pi[i].second-pi[j].first+1)));
//			}
		}
	}
//	sort(arr,arr+q-1);
//	ans-=max(0,arr[0]);
//	ans-=max(0,arr[1]);
//	for(int i=0;i<q;i++)
//		cout<<arr[i]<<" ";
	cout<<ans-mn<<endl;
//	for(int i=0;i<q;i++)
//		cout<<pi[i].first<<" "<<pi[i].second<<endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool cmp(pair<int,int> a,pair<int,int> b){
	if(a.first!=b.first)
		return a.first<b.first;
	else
		return a.second<b.second;
}
/*int arr[100100];
int num1l[100100];
int num1r[100100];
int num2l[100100];
int num2r[100100];
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		scanf("%d",&arr[i]);
		if(arr[i]==1){
			num1l[i]=num1r[i]=1;
		}
		else if(arr[i]==2){
			num2l[i]=num2r[i]=1;
		}
	}
	for(int i=1;i<n;i++){
		if(num1l[i]!=0)
			num1l[i]+=num1l[i-1];
		if(num21[i]!=0)
			num2l[i]+=num2l[i-1];
	}
	for(int i=n-1;i>=0;i--){
		if(num1[i]!=0)
			num1l[i]+=num1l[i-1];
		if(num21[i]!=0)
			num2l[i]+=num2l[i-1];
	}
}*/
pair<int,int> pi[5010];
int arr[5010],tot[5010];
int num1[5010],num2[5010];
priority_queue<int,vector<int>,greater<int> >qq;
int main()
{
	int n,q;
	cin>>n>>q;
	for(int i=0;i<q;i++){
		scanf("%d%d",&pi[i].first,&pi[i].second);
	}
	sort(pi,pi+q,cmp);
//	cout<<"123";
	for(int i=0,j=0;i<=5000;i++){
		while(pi[j].first==i&&j<q){
			qq.push(pi[j].second);
			j++;
		}
		tot[i]=qq.size();
		while(!qq.empty()&&qq.top()<i){
			qq.pop();
		}
	}
	if(tot[0]==1)
		num1[0]=1;
	else if(tot[0]==2)
		num2[0]=1;
	for(int i=1;i<=5000;i++){
		if(tot[i]==1){
			num1[i]=num1[i-1]+1;
			num2[i]=num2[i-1];
		}
		else if(tot[i]==2){
			num1[i]=num1[i-1];
			num2[i]=num2[i-1]+1;
		}
		else{
			num1[i]=num1[i-1];
			num2[i]=num2[i-1];
		}
	}
	int num=0;
	int ans=0;
	ans+=pi[0].second-pi[0].first+1;
	int mn=1000000000;
	int mx=pi[0].second;
	for(int i=1;i<q;i++){
		ans+=max(0,pi[i].second-max((pi[i].first-1),mx));
		mx=max(mx,pi[i].second);
	}
//	arr[0]=max(0,min(pi[1].first,pi[0].second+1)-pi[0].first);
//	for(int i=1;i<q-1;i++){
//		arr[i]=max(0,min(pi[i+1].first,pi[i].second+1)-max(pi[i].first,pi[i-1].second+1));
//	}
//	arr[q-1]=max(0,pi[q-1].second-max(pi[q-1].first-1,pi[q-2].second));
	for(int i=0;i<q;i++){
		for(int j=i+1;j<q;j++){
			if(pi[i].second<pi[j].first)
//				mn=max(0,min(mn,getans(pi[i].first,pi[i].second,0,1)+getans(pi[j].first,pi[j].second,0,1)));
				mn=min(mn,num1[pi[i].second]-num1[pi[i].first-1]+num1[pi[j].second]-num1[pi[j].first-1]);
			else{
//				mn=max(0,min(mn,getans(pi[i].first,pi[j].first-1,0,1)+getans(pi[i].second+1,pi[j].second,0,1)+getans(pi[j].first,pi[i].second,0,2)));
				mn=min(mn,num1[pi[j].first-1]-num1[pi[i].first-1]+num1[pi[j].second]-num1[pi[i].second-1]+num2[pi[i].second]-num2[pi[j].first-1]);

			}
		}
	}
	cout<<ans-mn<<endl;
}

/*
#include<bits/stdc++.h>
#include<time.h>
#include<conio.h>
#include<windows.h>
using namespace std;
string ch[21];
int main()
{
    int player1_y=rand()%5+1,player1_x=rand()%15+3,player2_y=rand()%5+35,player2_x=rand()%15+3,flag;
    int direction_x=1,direction_y=1;
    int ball_y=rand()%5+18,ball_x=rand()%5+8;
    char input;
    system("cls");
    fflush(stdin);
    for(int i=0;i<21;i++)
    	{
       	 	for(int j=0;j<41;j++)
        	{
            	if(i==0||i==20)
            	    ch[i]+='-';
            	else if(j==0||j==40)
            	    ch[i]+='|';
            	else if(j==20)
            		ch[i]+='I';
            	else if(i==ball_x&&j==ball_y)
            	    ch[i]+='*';
            	else if(j==player1_y&&abs(i-player1_x)<=2)
            	  	ch[i]+='|';
            	else if(j==player2_y&&abs(i-player2_x)<=2)
            	    ch[i]+='|';
            	else
            	  	ch[i]+=' ';
        	}
    	}
    while(1)
    {
    	for(int i=0;i<21;i++)
			ch[i].clear();
    	for(int i=0;i<21;i++)
    	{
       		for(int j=0;j<41;j++)
        	{
           		if(i==0||i==20)
	           	    ch[i]+='-';
   	        	else if(j==0||j==40)
        	    	ch[i]+='|';
            	else if(j==20)
            		ch[i]+='I';
            	else if(i==ball_x&&j==ball_y)
        	   	    ch[i]+='*';
           		else if(j==player1_y&&abs(i-player1_x)<=2)
           		  	ch[i]+='|';
      	    	else if(j==player2_y&&abs(i-player2_x)<=2)
           		    ch[i]+='|';
           		else
          	  		ch[i]+=' ';
        	}
    	}
        for(int i=0;i<21;i++)
        {
        	cout<<ch[i];
            printf("\n");
        }
        Sleep(100);
        system("cls");
        if(kbhit())
            input=getch();
        if(input=='W'||input=='w'&&player1_x>3)
            player1_x--;
        else if(input=='S'||input=='s'&&player1_x<17)
            player1_x++;
        else if(input=='A'||input=='a'&&player1_y>=2)
            player1_y--;
        else if(input=='D'||input=='d'&&player1_y<=4)
            player1_y++;

        if(input==75&&player2_y>=36)//左
            player2_y--;
        else if(input==77&&player2_y<=38)//右
            player2_y++;
        else if(input==72&&player2_x>3)//上
            player2_x--;
        else if(input==80&&player2_x<17)//下
            player2_x++;
        if(ball_x==1&&direction_x==-1||ball_x==19&&direction_x==1)
        	direction_x=(direction_x==1)?-1:1;
        if(ball_y==player1_y+1&&abs(ball_x-player1_x)<=2&&direction_y==-1)
        	direction_y=1;
        if(ball_y==player2_y-1&&abs(ball_x-player2_x)<=2&&direction_y==1)
        	direction_y=-1;
        ball_x+=direction_x;
        ball_y+=direction_y;
        if(ball_y==1&&direction_y==-1){
        	flag=2;
        	break;
		}
		else if(ball_y==39&&direction_y==1){
			flag=1;
			break;
		}
    }
    printf("player%d win",flag);
}
*/

/*
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
int main(){

}*/


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool cmp(pair<int,int> a,pair<int,int> b){
	if(a.first!=b.first)
		return a.first<b.first;
	else
		return a.second<b.second;
}
/*int arr[100100];
int num1l[100100];
int num1r[100100];
int num2l[100100];
int num2r[100100];
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		scanf("%d",&arr[i]);
		if(arr[i]==1){
			num1l[i]=num1r[i]=1;
		}
		else if(arr[i]==2){
			num2l[i]=num2r[i]=1;
		}
	}
	for(int i=1;i<n;i++){
		if(num1l[i]!=0)
			num1l[i]+=num1l[i-1];
		if(num21[i]!=0)
			num2l[i]+=num2l[i-1];
	}
	for(int i=n-1;i>=0;i--){
		if(num1[i]!=0)
			num1l[i]+=num1l[i-1];
		if(num21[i]!=0)
			num2l[i]+=num2l[i-1];
	}
}*/
pair<int,int> pi[5010];
int arr[5010],tot[5010];
int num1[5010],num2[5010];
priority_queue<int,vector<int>,greater<int> >qq;
int main()
{
	int n,q;
	cin>>n>>q;
	for(int i=0;i<q;i++){
		scanf("%d%d",&pi[i].first,&pi[i].second);
	}
	sort(pi,pi+q,cmp);
//	cout<<"123";
	for(int i=0,j=0;i<=5000;i++){
		while(pi[j].first==i&&j<q){
			qq.push(pi[j].second);
			j++;
		}
		while(!qq.empty()&&qq.top()<i){
			qq.pop();
		}
		tot[i]=qq.size();
	}
	if(tot[0]==1)
		num1[0]=1;
	else if(tot[0]==2)
		num2[0]=1;
	for(int i=1;i<=5000;i++){
		if(tot[i]==1){
			num1[i]=num1[i-1]+1;
			num2[i]=num2[i-1];
		}
		else if(tot[i]==2){
			num1[i]=num1[i-1];
			num2[i]=num2[i-1]+1;
		}
		else{
			num1[i]=num1[i-1];
			num2[i]=num2[i-1];
		}
	}
	int num=0;
	int ans=0;
	ans+=pi[0].second-pi[0].first+1;
	int mn=1000000000;
	int mx=pi[0].second;
	for(int i=1;i<q;i++){
		ans+=max(0,pi[i].second-max((pi[i].first-1),mx));
		mx=max(mx,pi[i].second);
	}
//	arr[0]=max(0,min(pi[1].first,pi[0].second+1)-pi[0].first);
//	for(int i=1;i<q-1;i++){
//		arr[i]=max(0,min(pi[i+1].first,pi[i].second+1)-max(pi[i].first,pi[i-1].second+1));
//	}
//	arr[q-1]=max(0,pi[q-1].second-max(pi[q-1].first-1,pi[q-2].second));
	for(int i=0;i<q;i++){
		for(int j=i+1;j<q;j++){
			if(pi[i].second<pi[j].first)
//				mn=max(0,min(mn,getans(pi[i].first,pi[i].second,0,1)+getans(pi[j].first,pi[j].second,0,1)));
				mn=min(mn,num1[pi[i].second]-num1[pi[i].first-1]+num1[pi[j].second]-num1[pi[j].first-1]);
			else{
//				mn=max(0,min(mn,getans(pi[i].first,pi[j].first-1,0,1)+getans(pi[i].second+1,pi[j].second,0,1)+getans(pi[j].first,pi[i].second,0,2)));
				mn=min(mn,num1[pi[j].first-1]-num1[pi[i].first-1]+num1[pi[j].second]-num1[pi[i].second-1]+num2[pi[i].second]-num2[pi[j].first-1]);

			}
		}
	}
	cout<<ans-mn<<endl;
}


￼￼
￼
| ￼ ￼
170104100115 | Logout

HOME
TOP
CONTESTS
GYM
PROBLEMSET
GROUPS
RATING
API
HELP
CALENDAR

PROBLEMSSUBMIT CODEMY SUBMISSIONSSTATUSHACKSSTANDINGSCUSTOM INVOCATION

My Submissions￼

#	When	Who	Problem	Lang	Verdict	Time	Memory
50880427	2019-03-06 11:40:20	170104100115	C - Painting the Fence	GNU C++11	Compilation error	0 ms	0 KB

My contest submissions￼

#	When	Who	Problem	Lang	Verdict	Time	Memory
50853771	2019-03-05 20:02:48	170104100115	F - Clear the String	GNU C++11	Accepted	62 ms	1000 KB
50842865	2019-03-05 19:06:27	170104100115	C - Painting the Fence	GNU C++11	Wrong answer on test 72	140 ms	200 KB
50842621	2019-03-05 19:05:30	170104100115	C - Painting the Fence	GNU C++11	Wrong answer on test 5	15 ms	100 KB
50842232	2019-03-05 19:03:42	170104100115	C - Painting the Fence	GNU C++11	Wrong answer on test 4	15 ms	100 KB
50840484	2019-03-05 18:55:27	170104100115	C - Painting the Fence	GNU C++11	Wrong answer on test 4	31 ms	100 KB
50832214	2019-03-05 18:23:51	170104100115	B - Discounts	GNU C++11	Accepted	249 ms	1200 KB
50826676	2019-03-05 18:12:23	170104100115	A - Regular Bracket Sequence	GNU C++11	Accepted	31 ms	0 KB

Educational Codeforces Round 61 (Rated for Div. 2)
Finished
Practice
￼

→ Virtual participation
Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ACM-ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest.
￼Start virtual contest

→ Practice
You are registered for practice. You can solve problems unofficially. Results can be found in the contest status and in the bottom of standings.

→ Clone Contest to Mashup
You can clone this contest to a mashup.

￼Clone Contest

→ Contest materials
Announcement￼

Codeforces (c) Copyright 2010-2019 Mike Mirzayanov
The only programming contests Web 2.0 platform
Server time: Mar/06/2019 16:41:36UTC+8 (d3).
Mobile version, switch to desktop version.
Privacy Policy
Supported by
￼ ￼
By 170104100115, contest: Educational Codeforces Round 61 (Rated for Div. 2), problem: (C) Painting the Fence, Wrong answer on test 72, #
 #include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=5005;
ll sum1[maxn],sum2[maxn];
int n,q,l[maxn],r[maxn],a[maxn];
int main()
{
	int n,q;ll ans=0,mi=1e9;scanf("%d%d",&n,&q);
	for(int i=1;i<=q;i++)
	{
		scanf("%d%d",&l[i],&r[i]);
		for(int j=l[i];j<=r[i];j++)
			a[j]++;
	}
	for(int i=1;i<=n;i++)
	{
		sum1[i]=sum1[i-1]+(a[i]==1);
		sum2[i]=sum2[i-1]+(a[i]>=1&&a[i]<=2);
		if(a[i]) ans++;
	}
	for(int i=1;i<=q;i++)
	{
		for(int j=i+1;j<=q;j++)
		{
			if(l[i]>r[j]||l[j]>r[i]) mi=min(mi,sum1[r[i]]-sum1[l[i]-1]+sum1[r[j]]-sum1[l[j]-1]);
			else if(l[i]<=l[j]&&r[j]<=r[i]) mi=min(mi,sum1[l[j]-1]-sum1[l[i]-1]+sum2[r[j]]-sum2[l[j]-1]+sum1[r[i]]-sum1[r[j]]);
			else if(l[j]<=l[i]&&r[i]<=r[j]) mi=min(mi,sum1[l[i]-1]-sum1[l[j]-1]+sum2[r[i]]-sum2[l[i]-1]+sum1[r[j]]-sum1[r[i]]);
			else if(l[i]<=r[j]) mi=min(mi,sum1[l[j]-1]-sum1[l[i]-1]+sum2[r[i]]-sum2[l[j]-1]+sum1[r[j]]-sum1[r[i]]);
			else mi=min(mi,sum1[l[i]-1]-sum1[l[j]-1]+sum2[r[j]]-sum2[l[i]-1]+sum1[r[i]]-sum1[r[j]]);
		}
	}
	printf("%lld\n",ans-mi);
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=5005;
ll sum1[maxn],sum2[maxn];
int n,q,l[maxn],r[maxn],a[maxn];
int main()
{
	int n,q;ll ans=0,mi=1e9;scanf("%d%d",&n,&q);
	for(int i=1;i<=q;i++)
	{
		scanf("%d%d",&l[i],&r[i]);
		for(int j=l[i];j<=r[i];j++)
			a[j]++;
	}
	for(int i=1;i<=n;i++)
	{
		sum1[i]=sum1[i-1]+(a[i]==1);
		sum2[i]=sum2[i-1]+(a[i]==2);
		if(a[i]) ans++;
	}
	for(int i=1;i<=q;i++)
	{
		for(int j=i+1;j<=q;j++)
		{
			if(l[i]>r[j]||l[j]>r[i]) mi=min(mi,sum1[r[i]]-sum1[l[i]-1]+sum1[r[j]]-sum1[l[j]-1]);
			else if(l[i]<=l[j]&&r[j]<=r[i]) mi=min(mi,sum1[l[j]-1]-sum1[l[i]-1]+sum2[r[j]]-sum2[l[j]-1]+sum1[r[i]]-sum1[r[j]]);
			else if(l[j]<=l[i]&&r[i]<=r[j]) mi=min(mi,sum1[l[i]-1]-sum1[l[j]-1]+sum2[r[i]]-sum2[l[i]-1]+sum1[r[j]]-sum1[r[i]]);
			else if(l[j]<=r[i]) mi=min(mi,sum1[l[j]-1]-sum1[l[i]-1]+sum2[r[i]]-sum2[l[j]-1]+sum1[r[j]]-sum1[r[i]]);
			else mi=min(mi,sum1[l[i]-1]-sum1[l[j]-1]+sum2[r[j]]-sum2[l[i]-1]+sum1[r[i]]-sum1[r[j]]);
		}
	}
	printf("%lld\n",ans-mi);
}


#include <iostream>
using namespace std;
int n,intervals,i,j,paintings,f[5005];
pair <int,int> a[5005];
int func(int x,int y)
{
    int rez=0;
    for (int p=x;p<=y;++p)
         if (f[p]-1==0) rez++;
    return rez;
}
int main()
{
    cin>>n>>intervals;
    for (i=1; i<=intervals; ++i)
    {
        cin>>a[i].first>>a[i].second;
        for (j=a[i].first; j<=a[i].second; ++j)
            f[j]++;
    }
    for (i=1;i<=intervals;++i)
    {
        for (j=i+1;j<=intervals;++j)
        {
            if (func(a[i].first,a[i].second)>func(a[j].first,a[j].second))
                swap(a[i],a[j]);
        }
    }
    for (i=a[1].first;i<=a[1].second;++i) f[i]--;
    for (i=a[2].first;i<=a[2].second;++i) f[i]--;
    for (i=1;i<=n;++i) if (f[i]>0) paintings++;
    cout<<paintings;
}


#include <iostream>
#include <algorithm>
using namespace std;
int n,intervals,i,j,paintings,f[5005];
pair <int,int> a[5005],b[5005];
int main()
{
    cin>>n>>intervals;
    for (i=1; i<=intervals; ++i)
    {
        cin>>a[i].first>>a[i].second;
        b[i].first=a[i].second-a[i].first+1;
        b[i].second=i;
        for (j=a[i].first;j<=a[i].second;++j)
             f[j]++;
    }
    sort(b+1,b+intervals+1);
    for (i=a[b[1].second].first;i<=a[b[1].second].second;++i) f[i]--;
    for (i=a[b[2].second].first;i<=a[b[2].second].second;++i) f[i]--;
    for (i=1;i<=n;++i) if (f[i]>0) paintings++;
    cout<<paintings;
}


#include <iostream>
#include <algorithm>
using namespace std;
int n,intervals,i,j,paintings,f[5005];
pair <int,int> a[5005],b[5005];
int main()
{
    cin>>n>>intervals;
    for (i=1; i<=intervals; ++i)
    {
        cin>>a[i].first>>a[i].second;
        b[i].first=a[i].second-a[i].first+1;
        b[i].second=i;
        for (j=a[i].first;j<=a[i].second;++j)
             f[j]++;
    }
    sort(b+1,b+intervals+1);
    for (i=a[b[1].second].first;i<=a[b[1].second].second;++i) f[i]--;
    for (i=a[b[2].second].first;i<=a[b[2].second].second;++i) f[i]--;
    for (i=1;i<=n;++i) if (f[i]) paintings++;
    cout<<paintings;
}


#include <iostream>
#include <algorithm>
using namespace std;
int n,intervals,i,j,paintings,f[5005];
pair <int,int> a[5005];
bool cmp(pair <int,int> x,pair <int,int> y)
{
    int rez=0,rez1=0;
    for (int p=x.first;p<=x.second;++p)
         if (f[p]-1==0) rez++;
    for (int p=y.first;p<=y.second;++p)
         if (f[p]-1==0) rez1++;
    if (rez>rez1) return 0;
    return 1;
}
int main()
{
    cin>>n>>intervals;
    for (i=1; i<=intervals; ++i)
    {
        cin>>a[i].first>>a[i].second;
        for (j=a[i].first; j<=a[i].second; ++j)
            f[j]++;
    }
    sort(a+1,a+intervals+1,cmp);
    for (i=a[1].first;i<=a[1].second;++i) f[i]--;
    for (i=a[2].first;i<=a[2].second;++i) f[i]--;
    for (i=1;i<=n;++i) if (f[i]>0) paintings++;
    cout<<paintings;
}


#include <iostream>
#include <algorithm>
using namespace std;
int n,intervals,i,j,paintings,f[5005];
pair <int,int> a[5005];
bool cmp(pair <int,int> x,pair <int,int> y)
{
    int rez=0,rez1=0;
    for (int p=x.first;p<=x.second;++p)
         rez+=f[p]-1;
    for (int p=y.first;p<=y.second;++p)
         rez+=f[p]-1;
    if (rez<rez1) return 0;
    return 1;
}
int main()
{
    cin>>n>>intervals;
    for (i=1; i<=intervals; ++i)
    {
        cin>>a[i].first>>a[i].second;
        for (j=a[i].first; j<=a[i].second; ++j)
            f[j]++;
    }
    sort(a+1,a+intervals+1,cmp);
    for (i=a[1].first;i<=a[1].second;++i) f[i]--;
    for (i=a[2].first;i<=a[2].second;++i) f[i]--;
    for (i=1;i<=n;++i) if (f[i]>0) paintings++;
    cout<<paintings+1;
}


#include <iostream>
#include <cstring>
using namespace std;
const int N = 5e3+10;
int n,s,i,j,jj,unu,maxx,minn,still_painted,l[N],r[N],c[N],d[N];
int main()
{
    cin>>s>>n;
    for (i=1; i<=n; ++i)
    {
        cin>>l[i]>>r[i];
        for (j=l[i]; j<=r[i]; ++j)
            c[j]++;
    }
    for (i=1; i<=n; ++i)
    {
        minn=INT_MAX;
        still_painted=0;
        memset(d,0,4*(s+1));
        for (j=l[i]; j<=r[i]; ++j)
             c[j]--;
        for (j=1; j<=s; ++j)
        {
            if (c[j]==1)
                d[j]=1;
            if (c[j])
                still_painted++;
        }
        for (j=1; j<=n; ++j)
        {
            if (j!=i)
            {
                unu=0;
                for (jj=l[j]; jj<=r[j]; ++jj)
                    if (d[jj])
                        unu++;
                minn=min(minn,unu);
            }
        }
        maxx=max(maxx,still_painted-minn);
        for (j=l[i]; j<=r[i]; ++j)
             c[j]++;
    }
    cout<<maxx;
}


#include <iostream>
#include <cstring>
using namespace std;
const int N = 5e3+10;
int n,s,i,j,maxx,minn,still_painted,l[N],r[N],c[N],p[N];
int main()
{
    cin>>s>>n;
    for (i=1; i<=n; ++i)
    {
        cin>>l[i]>>r[i];
        for (j=l[i]; j<=r[i]; ++j)
            c[j]++;
    }
    for (i=1; i<=n; ++i)
    {
        minn=INT_MAX;
        still_painted=0;
        memset(p,0,4*(s+1));
        for (j=l[i]; j<=r[i]; ++j) c[j]--;
        for (j=1; j<=s; ++j)
        {
            if (c[j]==1) p[j]=p[j-1]+1;
            else p[j]=p[j-1];
            if (c[j]) still_painted++;
        }
        for (j=i+1; j<=n; ++j)
            minn=min(minn,p[r[j]]-p[l[j]]-(p[l[j]]!=p[l[j]-1] ? -1 : 0));
        maxx=max(maxx,still_painted-minn);
        for (j=l[i]; j<=r[i]; ++j) c[j]++;
    }
    cout<<maxx;
}


#include <iostream>
#include <algorithm>
using namespace std;
int n,intervals,i,j,paintings,f[5005];
pair <int,int> a[5005];
bool cmp(const pair <int,int> x,const pair <int,int> y)
{
    int rez=0,rez1=0;
    for (int p=x.first;p<=x.second;++p)
         if (f[p]-1==0) rez++;
    for (int p=y.first;p<=y.second;++p)
         if (f[p]-1==0) rez1++;
    if (rez>rez1) return 0;
    return 1;
}
int main()
{
    cin>>n>>intervals;
    for (i=1; i<=intervals; ++i)
    {
        cin>>a[i].first>>a[i].second;
        for (j=a[i].first; j<=a[i].second; ++j)
            f[j]++;
    }
    sort(a+1,a+intervals+1,cmp);
    for (i=a[1].first;i<=a[1].second;++i) f[i]--;
    for (i=a[2].first;i<=a[2].second;++i) f[i]--;
    for (i=1;i<=n;++i) if (f[i]>0) paintings++;
    cout<<paintings;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2

  88 3
  1 3
  1 5
  3 8
  ans = 6
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
VI A,B,sum,pos; int n,q;

int drop(const int i)
{
    FOR(j,1,n+1)
        B[j] = A[j];
    FOR(j,I[i].a,I[i].b+1)
        B[j]--;
    int ans = 0; pos.clear();
    FOR(j,1,n+1) {
        B[j] = min(2,B[j]);
        if (B[j] == 1)
            pos.push_back(j);
        ans += (B[j] > 0);
    }
    FOR(j,1,n+1)
        sum[j] = sum[j-1]+B[j];
    FOR(k,0,q) if (k != i) {
        const int a = I[k].a;
        const int b = I[k].b;
        const int s = sum[b]-sum[a-1];
        if (s == (b-a+1)*2)
            return ans;
    }
    int best = n;
    FOR(k,0,q) if (k != i) {
        const int p1 = *  lower_bound(ALL(pos), I[k].a);
        const int p2 = *--upper_bound(ALL(pos), I[k].b);
        best = min(best, p2-p1+1);
    }
    return ans-best;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        A = B = sum = VI(n+1);
        FOR(i,0,q) {
            cin >> I[i].a >> I[i].b;
            FOR(j,I[i].a,I[i].b+1)
                A[j]++;
        }
        int ans = 0;
        FOR(i,0,q)
            ans = max(ans, drop(i));
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2

  88 3
  1 3
  1 5
  3 8
  ans = 6
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

const int inf = 1e9;
const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
/* dp(i,j) the last used is i, and already skipped j */
int n,q, dp[maxq][3];

bool cmp(const Interval& x, const Interval& y)
{
    if (x.a == y.a)
        return x.b < y.b;
    return x.a < y.a;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        FOR(i,1,q+1)
            cin >> I[i].a >> I[i].b;
        sort(I+1,I+q+1,cmp);
        I[0].a = I[0].b = -inf;
        FOR(i,0,q+1) FOR(j,0,3)
            dp[i][j] = -inf;
        dp[0][0] = 0;
        FOR(i,1,q+1) FORR(j,q,-1) if (j < i) {
            int res  = I[i].b - I[i].a + 1;
            if (I[j].b >= I[i].a)
                res -= I[j].b - I[i].a + 1;
            /* use i, this loop has to be before the not use i loop */
            FORR(k,2,-1) {
                dp[i][k] = max(dp[i][k], dp[j][k] + res);
                /* printf("%d  %d,%d = %d\n",i,i,k,dp[i][k]); */
            }
            /* not use i */
            FORR(k,1,-1) {
                dp[j][k+1] = max(dp[j][k+1], dp[j][k]);
                /* printf("%d  %d,%d = %d\n",i,j,k+1,dp[j][k+1]); */
            }
        }
        int ans = 0;
        FOR(i,1,q+1)
            ans = max(ans, dp[i][2]);
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
VI A,B; int n,q;

int drop(const int i)
{
    FOR(j,1,n+1)
        B[j] = A[j];
    FOR(j,I[i].a,I[i].b+1)
        B[j]--;
    int ans = 0; VI pos;
    FOR(j,1,n+1) {
        B[j] = min(2,B[j]);
        if (B[j] == 1)
            pos.push_back(j);
        ans += (B[j] > 0);
    }
    VI sum(n+1);
    FOR(j,1,n+1)
        sum[j] = sum[j-1]+B[j];
    FOR(k,0,q) if (k != i) {
        const int a = I[k].a;
        const int b = I[k].b;
        const int s = sum[b]-sum[a-1];
        if (s == (b-a+1)*2)
            return ans;
    }
    int best = n;
    FOR(k,0,q) if (k != i) {
        const int p = *lower_bound(ALL(pos), I[k].a);
        best = min(best, I[k].b-p+1);
    }
    return ans-best;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        A = B = VI(n+1);
        FOR(i,0,q) {
            cin >> I[i].a >> I[i].b;
            FOR(j,I[i].a,I[i].b+1)
                A[j]++;
        }
        int ans = 0;
        FOR(i,0,q)
            ans = max(ans, drop(i));
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2

  88 3
  1 3
  1 5
  3 8
  ans = 6
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

/* greedy does not work */

const int inf = 1e9;
const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
int n,q, dp[maxq][3];

bool cmp(const Interval& x, const Interval& y)
{
    if (x.a == y.a)
        return x.b < y.b;
    return x.a < y.a;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        FOR(i,1,q+1)
            cin >> I[i].a >> I[i].b;
        sort(I+1,I+q+1,cmp);
        I[0].a = I[0].b = -inf;
        FOR(i,0,q+1) FOR(j,0,3)
            dp[i][j] = -inf;
        dp[0][0] = 0;
        FOR(i,1,q+1) {
            FORR(j,q,-1) if (j < i) {
                if (I[j].b >= I[i].b)
                    continue;
                int res  = I[i].b - I[i].a + 1;
                if (I[j].b >= I[i].a)
                    res -= I[j].b - I[i].a + 1;
                FORR(k,2,-1) {
                    dp[i][k] = max(dp[i][k], dp[j][k] + res);
                    /* printf("%d  %d,%d = %d\n",i,i,k,dp[i][k]); */
                }
                FORR(k,1,-1) {
                    dp[j][k+1] = max(dp[j][k+1], dp[j][k]);
                    /* printf("%d  %d,%d = %d\n",i,j,k+1,dp[j][k+1]); */
                }
            }
        }
        int ans = 0;
        FOR(i,1,q+1)
            ans = max(ans, dp[i][2]);
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
VI A; int n,q;

int drop(const int i)
{
    VI B = A; int ans = 0;
    FOR(j,I[i].a,I[i].b+1)
        B[j]--;
    FOR(j,1,n+1) {
        B[j] = min(2,B[j]);
        ans += (B[j] > 0);
    }
    VI sum(n+1);
    FOR(j,1,n+1)
        sum[j] = sum[j-1]+B[j];
    FOR(k,0,q) if (k != i) {
        const int a = I[k].a;
        const int b = I[k].b;
        const int s = sum[b]-sum[a-1];
        if (s == (b-a+1)*2)
            return ans;
    }
    int best = n, cnt = 0;
    FOR(i,1,n+1) {
        if (B[i] != 1) {
            if (cnt)
                best = min(best,cnt);
            cnt = 0;
        }
        else
            cnt++;
    }
    if (cnt)
        best = min(best,cnt);
    return ans-best;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        A = VI(n+1);
        FOR(i,0,q) {
            cin >> I[i].a >> I[i].b;
            FOR(j,I[i].a,I[i].b+1)
                A[j]++;
        }
        int ans = 0;
        FOR(i,0,q)
            ans = max(ans, drop(i));
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

typedef bool (*Cmp)(const PII&, const PII&);

bool cmp(const PII& a, const PII& b)
{ return a.second-a.first < b.second-b.first; }

ostream& operator<< (ostream& os, const PII& x)
{ return os << x.first << "," << x.second << " " << x.second-x.first; }

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    int n,q;
    while (cin >> n >> q) {
        VI A(n+1);
        priority_queue<PII, vector<PII>, Cmp> Q(cmp);
        FOR(i,0,q) {
            int a,b; cin >> a >> b;
            Q.push(PII(a,b));
        }
        q -= 2;
        while (q && Q.size()) {
            PII x = Q.top(); Q.pop(); bool use = true;
            while (A[x.first] && x.first < x.second)
                use = false, x.first++;
            while (A[x.second] && x.first < x.second)
                use = false, x.second--;
            if (x.first == x.second && A[x.first])
                continue;
            if (use) {
                FOR(i,x.first,x.second+1)
                    A[i] = 1;
                q--;
            }
            else {
                Q.push(x);
            }
        }
        int ans = 0;
        FOR(i,1,n+1)
            ans += A[i];
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2

  88 3
  1 3
  1 5
  3 8
  ans = 6
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

/* greedy does not work */

const int inf = 1e9;
const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
int n,q, dp[maxq][3];

bool cmp(const Interval& x, const Interval& y)
{
    if (x.a == y.a)
        return x.b < y.b;
    return x.a < y.a;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        FOR(i,1,q+1)
            cin >> I[i].a >> I[i].b;
        sort(I+1,I+q+1,cmp);
        I[0].a = I[0].b = -inf;
        FOR(i,0,q+1) FOR(j,0,3)
            dp[i][j] = -inf;
        dp[0][0] = 0;
        FOR(i,1,q+1) {
            FORR(j,q,-1) if (j < i) {
                if (I[j].b >= I[i].b)
                    continue;
                int res  = I[i].b - I[i].a + 1;
                if (I[j].b >= I[i].a)
                    res -= I[j].b - I[i].a + 1;
                FORR(k,2,-1) {
                    if (k != 2)
                        dp[j][k+1] = max(dp[j][k+1], dp[j][k]);
                    dp[i][k] = max(dp[i][k], dp[j][k] + res);
                }
            }
        }
        int ans = 0;
        FOR(i,1,q+1)
            ans = max(ans, dp[i][2]);
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2

  88 3
  1 3
  1 5
  3 8
  ans = 6
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
VI A,B; int n,q;

int drop(const int i)
{
    FOR(j,1,n+1)
        B[j] = A[j];
    FOR(j,I[i].a,I[i].b+1)
        B[j]--;
    int ans = 0; VI pos;
    FOR(j,1,n+1) {
        B[j] = min(2,B[j]);
        if (B[j] == 1)
            pos.push_back(j);
        ans += (B[j] > 0);
    }
    VI sum(n+1);
    FOR(j,1,n+1)
        sum[j] = sum[j-1]+B[j];
    FOR(k,0,q) if (k != i) {
        const int a = I[k].a;
        const int b = I[k].b;
        const int s = sum[b]-sum[a-1];
        if (s == (b-a+1)*2)
            return ans;
    }
    int best = n;
    FOR(k,0,q) if (k != i) {
        const int p1 = *  lower_bound(ALL(pos), I[k].a);
        const int p2 = *--upper_bound(ALL(pos), I[k].b);
        best = min(best, p2-p1+1);
    }
    return ans-best;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        A = B = VI(n+1);
        FOR(i,0,q) {
            cin >> I[i].a >> I[i].b;
            FOR(j,I[i].a,I[i].b+1)
                A[j]++;
        }
        int ans = 0;
        FOR(i,0,q)
            ans = max(ans, drop(i));
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2

  88 3
  1 3
  1 5
  3 8
  ans = 6
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
VI A,B,sum; int n,q;

int drop(const int i)
{
    FOR(j,1,n+1)
        B[j] = A[j];
    FOR(j,I[i].a,I[i].b+1)
        B[j]--;
    int ans = 0; VI pos;
    FOR(j,1,n+1) {
        B[j] = min(2,B[j]);
        if (B[j] == 1)
            pos.push_back(j);
        ans += (B[j] > 0);
    }
    FOR(j,1,n+1)
        sum[j] = sum[j-1]+B[j];
    FOR(k,0,q) if (k != i) {
        const int a = I[k].a;
        const int b = I[k].b;
        const int s = sum[b]-sum[a-1];
        if (s == (b-a+1)*2)
            return ans;
    }
    int best = n;
    FOR(k,0,q) if (k != i) {
        const int p1 = *  lower_bound(ALL(pos), I[k].a);
        const int p2 = *--upper_bound(ALL(pos), I[k].b);
        best = min(best, p2-p1+1);
    }
    return ans-best;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        A = B = sum = VI(n+1);
        FOR(i,0,q) {
            cin >> I[i].a >> I[i].b;
            FOR(j,I[i].a,I[i].b+1)
                A[j]++;
        }
        int ans = 0;
        FOR(i,0,q)
            ans = max(ans, drop(i));
        cout << ans << endl;
    }
    return 0;
}


/*
  Educational Codeforces Round 61 (Rated for Div. 2)
  C. Painting the Fence
  time limit per test 2 seconds
  memory limit per test 256 megabytes

  You have a long fence which consists of n sections. Unfortunately, it
  is not painted, so you decided to hire q painters to paint it. i-th
  painter will paint all sections x such that li<=x<=ri.

  Unfortunately, you are on a tight budget, so you may hire only q-2
  painters. Obviously, only painters you hire will do their work.

  You want to maximize the number of painted sections if you choose q-2
  painters optimally. A section is considered painted if at least one
  painter paints it.

  Input

  The first line contains two integers n and q (3<=n,q<=5000) - the
  number of sections and the number of painters availible for hire,
  respectively.

  Then q lines follow, each describing one of the painters: i-th line
  contains two integers li and ri (1<=li<=ri<=n).

  Output

  Print one integer - maximum number of painted sections if you hire q-2
  painters.

  Examples

  Input

  7 5
  1 4
  4 5
  5 6
  6 7
  3 5

  Output

  7

  Input

  4 3
  1 1
  2 2
  3 4

  Output

  2

  Input

  4 4
  1 1
  2 2
  2 3
  3 4

  Output

  3

  100 5
  20 25
  17 21
  24 28
  1 2
  30 33
  ans = 14

  3 3
  1 1
  1 1
  2 3
  ans = 2

  88 3
  1 3
  1 5
  3 8
  ans = 6
*/

#include <bits/stdc++.h>

using namespace std;

/* g++ -g -fsanitize=address -lasan -std=c++11 -Dfoo_ */

/* freopen("input.txt", "rt", stdin); */
/* freopen("output.txt", "wt", stdout); */

#define ALL(c)          (c).begin(), (c).end()
#define ALLR(c)         (c).rbegin(), (c).rend()
#define FOR(i,a,b)      for (int i=(a); i < (b); ++i)
#define FORR(i,a,b)     for (int i=(a); i > (b); --i)
#define FOR_ALL(i,c)    for (__typeof((c).begin()) i=(c).begin();   \
                             i != (c).end(); ++i)
#define FOR_ALLR(i,c)   for (__typeof((c).rbegin()) i=(c).rbegin(); \
                             i != (c).rend(); ++i)
#define SZ(array)       (sizeof(array)/sizeof(array[0]))
#define lc(x)           (x<<1)     /* 2*x */
#define rc(x)           (x<<1 | 1) /* 2*x+1 */
#define lowbit(x)       (x & (-x)) /* 0b10100 -> 0b100 */

typedef long long       LL;
typedef map<int,int>    MII;
typedef pair<int,int>   PII;
typedef set<int>        SI;
typedef vector<bool>    VB;
typedef vector<double>  VD;
typedef vector<int>     VI;
typedef vector<string>  VS;

/* check if a key is in container C */
template <class C>
inline bool in_(const typename C::key_type& k, const C& A)
{ return A.find(k) != A.end(); }
inline bool in_(const string& s, const string& S)
{ return S.find(s) != string::npos; }

/* greedy does not work */

const int inf = 1e9;
const int maxq = 5e3+5;
struct Interval { int a,b; } I[maxq];
int n,q, dp[maxq][3];

bool cmp(const Interval& x, const Interval& y)
{
    if (x.a == y.a)
        return x.b < y.b;
    return x.a < y.a;
}

int main()
{
#ifdef foo_
    freopen("foo", "rt", stdin);
#endif
    ios::sync_with_stdio(false);
    while (cin >> n >> q) {
        FOR(i,1,q+1)
            cin >> I[i].a >> I[i].b;
        sort(I+1,I+q+1,cmp);
        I[0].a = I[0].b = -inf;
        FOR(i,0,q+1) FOR(j,0,3)
            dp[i][j] = -inf;
        dp[0][0] = 0;
        FOR(i,1,q+1) {
            FORR(j,q,-1) if (j < i) {
                int res  = I[i].b - I[i].a + 1;
                if (I[j].b >= I[i].a)
                    res -= I[j].b - I[i].a + 1;
                FORR(k,2,-1) {
                    dp[i][k] = max(dp[i][k], dp[j][k] + res);
                    /* printf("%d  %d,%d = %d\n",i,i,k,dp[i][k]); */
                }
                FORR(k,1,-1) {
                    dp[j][k+1] = max(dp[j][k+1], dp[j][k]);
                    /* printf("%d  %d,%d = %d\n",i,j,k+1,dp[j][k+1]); */
                }
            }
        }
        int ans = 0;
        FOR(i,1,q+1)
            ans = max(ans, dp[i][2]);
        cout << ans << endl;
    }
    return 0;
}


#include <bits/stdc++.h>

#define ff first
#define ss second
#define mp make_pair

using namespace std;

short n,q,dp[5005][5005][3];
bool mark[5005][5005][3];
pair<short,short> v[5005];

short f(int i, int j, int k) {
	if(i == q) return k == 0 ? 0 : -1e4;
	if(mark[i][j][k]) return dp[i][j][k];
	mark[i][j][k] = true;

	short ret = 0;
	if(v[i].ss > j) ret = f(i+1, max<int>(j, v[i].ss), k) + min(v[i].ss - j, v[i].ss - v[i].ff+1);
	if(k) ret = max(ret, f(i+1, j, k-1));

	return dp[i][j][k] = ret;
}

int main() {
	scanf("%hd%hd", &n, &q);

	for(int i = 0; i < q; i++)
		scanf("%hd%hd", &v[i].ff, &v[i].ss);

	sort(v, v+q);

	printf("%hd\n", f(0,0,2));
    return 0;
}


#include <bits/stdc++.h>

#define ff first
#define ss second
#define mp make_pair

using namespace std;

short n,q,dp[5005][5005][3];
bool mark[5005][5005][3];
pair<short,short> v[5005];

short f(int i, int j, int k) {
	if(i == q) return k == 0 ? 0 : -1e4;
	if(mark[i][j][k]) return dp[i][j][k];
	mark[i][j][k] = true;

	short ret = 0;
	if(v[i].ss > j) ret = f(i+1, v[i].ss, k) + min(v[i].ss - j, v[i].ss - v[i].ff+1);
	else ret = f(i+1, j, k);
	if(k) ret = max(ret, f(i+1, j, k-1));

	return dp[i][j][k] = ret;
}

int main() {
	scanf("%hd%hd", &n, &q);

	for(int i = 0; i < q; i++)
		scanf("%hd%hd", &v[i].ff, &v[i].ss);

	sort(v, v+q);

	printf("%hd\n", f(0,0,2));
    return 0;
}


#include <bits/stdc++.h>

#define ff first
#define ss second
#define mp make_pair

using namespace std;

int l[5005], r[5005];
int tot[5005], aux[5005], tmp[5005];

int main() {
	int n, q;

	scanf("%d%d", &n, &q);

	for(int i = 0; i < q; i++) {
		scanf("%d%d", &l[i], &r[i]);
		tot[l[i]]++;
		tot[r[i]+1]--;
	}

	int sum = 0;

	// for(int i = 1; i <= n; i++) {
	// 	tot[i] += tot[i-1];
	// 	if(tot[i] > 0) sum++;
	// }

	int best = 0;
	for(int i = 0; i < q; i++) {
		for(int j = 0; j <= n; j++)
			aux[j] = tot[j];
		aux[l[i]]--;
		aux[r[i]+1]++;
		int cur = 0;
		for(int j = 1; j <= n; j++) {
			aux[j] += aux[j-1];
			if(aux[j] > 0) cur++;
			if(aux[j] == 1) tmp[j]++;
			tmp[j] += tmp[j-1];
		}
		for(int j = i+1; j < q; j++) {
			int ones = tmp[r[j]] - tmp[l[j]-1];
			best = max(best, cur - ones);
		}

		for(int j = 1; j <= n; j++)
			tmp[j] = 0;
	}

	printf("%d\n", best);

    return 0;
}


#include "bits/stdc++.h"
using namespace std;

#define  F  first
#define  S  second
#define  pb push_back
#define  mp make_pair
typedef long long int ll;
const int N=1e6+6,inf=1e9+7;
bool vis[102][102],mark[102];
void dfs(int len,int &cnt,int u,int st,int n)
{
    mark[u]=1;
    if(len==0)
    {
        mark[u]=0;
        if(vis[st][u])
            cnt++;
        return;
    }
    for(int i=0;i<n;i++)
    {
        if(mark[i]||!vis[u][i])continue;
        dfs(len-1,cnt,i,st,n);
    }
    mark[u]=0;
}
int _count(int n)
{
    int cnt=0;
    for(int i=0;i<n-2;i++)
    {
        dfs(2,cnt,i,i,n);
        mark[i]=1;
    }
    return cnt/2;
}
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int n;cin>>n;
    int lo=3,hi=100,mid,cur=0;
    while(lo<=hi)
    {
        mid=(lo+hi)>>1;
        memset(mark,0,sizeof mark);
        memset(vis,0,sizeof vis);
        for(int i=0;i<mid;i++)
            for(int j=i+1;j<mid;j++)
                vis[i][j]=vis[j][i]=1;
        int ret=_count(mid);
        if(ret>n)hi=mid-1;
        else cur=mid,lo=mid+1;
    }
    memset(mark,0,sizeof mark);
    memset(vis,0,sizeof vis);
    for(int i=0;i<cur;i++)
        for(int j=i+1;j<cur;j++)
            vis[i][j]=vis[j][i]=1;
    if(_count(cur)==n)
    {
        cout<<cur<< "\n";
        for(int i=0;i<cur;i++)
        {
            for(int j=0;j<cur;j++)
                cout<<vis[i][j];
            cout<< "\n";
        }
    }
    else
    {
        for(int i=0;i<cur;i++)
        {
            memset(mark,0,sizeof mark);
            vis[i][cur]=vis[cur][i]=1;
            int ret=_count(cur+1);
            if(ret==n)break;
        }
        cout<<cur+1<< "\n";
        for(int i=0;i<cur+1;i++)
        {
            for(int j=0;j<cur+1;j++)
                cout<<vis[i][j];
            cout<< "\n";
        }
    }

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int g[123][123];
int main()
{
	int k;
	cin>>k;//要求的三元环个数
	for(int i=0;i<90;i++)//依次增加顶点
	{
		int sum = 0;//三元环个数
		for(int j = 0; j < i && sum <= k;j++)
		{
			k-=sum;
			sum++;
			g[i][j] = g[j][i] = 1;
		}
	 }
	cout<<90<<endl;
	for(int i=0;i<90;i++)
	{
		for(int j=0;j<90;j++)
		{
			int ans = g[i][j] ? 1:0;
			cout<<ans;
		}
		cout<<endl;
	}
	return 0;
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define IOS {ios :: sync_with_stdio(false); cin.tie(0);cout.tie(0); }
#define F first
#define S second
#define pb push_back
typedef long double ld;
#define deci(n) cout << fixed << setprecision(n);
typedef long long ll;
#define all(a) a.begin(), a.end()
#define pll pair<ll, ll>
#define bits(x) __builtin_popcount(x)
#define fori(n)  for (ll i = 0; i < n; i++)
#define fori2(n) for(ll i=1;i<=n;i++)
#define forj(n)  for (ll j = 0; j < n; j++)
#define forj2(n) for(ll j=1;j<=n;j++)
#define fork(n)  for (ll k = 0; k < n; k++)
#define fork2(n) for(ll k=1;k<=n;k++)
#define vll vector <ll>
#define mll map <ll, ll>
#define vpll vector <pll>
const ll md = 1e9 + 7;
const ll N = 105;
// ll fac[N] = {1};
// #define calfac for(ll i=1  ;i<N;i++) fac[i] = (fac[i-1]*i);
ll C[N+1][4];
void  ncr(){
    ll n = N,k = 3;
    for (ll i = 0; i <= n; i++) {
        for (ll j = 0; j <= min(i, k); j++) {
            if (j == 0 || j == i)  C[i][j] = 1;
            else C[i][j] = C[i - 1][j - 1] +  C[i - 1][j];
        }
    }
}

#define BSET(a, p) ((a) | (1ll << (p)))
#define BCHK(a, p) ((a) & (1ll << (p)))
#define BXOR(a, p) ((a) ^ (1ll << (p)));
#define BREM(a, p) (BCHK(a, p)?(BXOR(a, p)):(a))
#define BSHO(a, N) (bitset<N>(a))

#define RBTTYPE int
#define ordered_set tree<RBTTYPE, null_type, less<RBTTYPE>, rb_tree_tag,tree_order_statistics_node_update>

ll modexp(ll x, ll ex) {
    ll ans = 1ll;
    while (ex > 0) {
        if (ex & 1ll) ans = (ans * x) % md;
        ex >>= 1ll;
        x = (x * x) % md;
    }
    return ans;
}
ll modInv(ll a)
{
    return pow(a,md-2);
}

// ll nCr(ll n,ll r)
// {
//     // return (fac[n]*modInv((fac[r]*fac[n-r])%md))%md;
//     return fac[n]/(fac[r]*fac[n-r]);
// }

vll v;
char e[105][105];
int32_t main(){
    IOS;
    ncr();
    ll bs=0,i,j,k,n,m;
    cin >> k;

    for(i=100;i>=3;i--){
        if(C[i][3]<=k){
            bs = i;
            break;
        }
    }
    // k -= nCr(bs,3);
    k -= C[bs][3];
    ll cnt = bs;
    for(j=bs;j>=2;j--){
        while(C[j][2]<=k){
            k -= C[j][2];
            v.pb(j);
            cnt++;
        }
    }
    cout << cnt <<"\n";
    for(i=0;i<bs;i++){

        for(j=0;j<bs;j++){
            if(i==j) continue;
            e[i][j] = '1';
            e[j][i] = '1';
        }
    }
    for(i=0;i<v.size();i++){
        ll p = bs + i;
        for(j=0;j<v[i];j++){
            e[p][j] = '1';
            e[j][p] = '1';
        }
    }
    for(i=0;i<cnt;i++){
        forj(cnt){
            if(e[i][j]!='1') cout<<"0";
            else cout <<"1";
        }
        cout <<"\n";
    }
}


#include <bits/stdc++.h>
using namespace std;
int cnt[102];
int main() {
    cnt[3] = 1;
    for(int i = 4; i <= 101; i++) {
        cnt[i] = (i*(i-1)*(i-2))/6;
    //    cout << cnt[i] << " ";
    }
    int n;
    cin >> n;
    auto it = lower_bound(cnt, cnt + 102, n);
    int p = it-cnt;
    cout << p << endl;
    for(int i = 0; i < p; i++) {
        for(int j = 0; j < p; j++) cout << ((i==j) ? 0 : 1);
        cout << endl;
    }
    return 0;
}


#include <iostream>

using namespace std;

int main()
{
    int cycles;
    cin >> cycles;
    bool a[100][100]= {0};
    int point = 1;
    int i = 0 ;
    while(cycles>0)
    {
        if(cycles<i){
            i=0;
            point++;
        }
        a[i][point]=1;
        a[point][i]=1;
        cycles-=i;
        i++;
        if(i>=point&&cycles>0){
            i=0;
            point++;
        }
    }
    cout << point+1<< endl;
    for(int i=0;i<=point;i++){
        for(int j=0;j<=point;j++){
            cout << a[i][j];
        }
        cout << endl;
    }
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

using namespace std;

int a[105][105];

int main(){
	fastio
	int n, ans = 0;
	cin >> n;
	while(n){
		for(int i = 100;i > 0;i--){
			if(i*(i-1)*(i-2)/6<=n){
				ans += i;
				for(int u = 0;u < ans;u++)
					for(int v = 0;v < ans;v++)
						a[u][v] = (u!=v);
				n-=i*(i-1)*(i-2)/6;
				for(int j = i;j >= 2;j--){
					if(j*(j-1)/2<=n){
						ans++;
						for(int k = ans-j-1;k < ans-1;k++) a[k][ans-1] = a[ans-1][k] = 1;
						n -= j*(j-1)/2;
						for(int k = j+1;k >= 2;k--){
							if(k*(k-1)/2<=n){
								ans++;
								for(int b = ans-k-1;b < ans-1;b++) a[b][ans-1] = a[ans-1][b] = 1;
								n -= k*(k-1)/2;
								break;
							}
						}
						break;
					}
				}
				break;
			}
		}
	}
	cout << ans << "\n";
	for(int i = 0;i < ans;i++){
		for(int j = 0;j < ans;j++) cout << a[i][j];
		cout << "\n";
	}
}


#include <bits/stdc++.h>

#define ll long long
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

using namespace std;

int a[105][105];

int main(){
	fastio
	int n, ans = 0;
	cin >> n;
	while(n){
		for(int i = 100;i > 0;i--){
			if(i*(i-1)*(i-2)/6<=n){
				ans += i;
				for(int u = ans-i;u < ans;u++)
					for(int v = ans-i;v < ans;v++)
						a[u][v] = (u!=v);
				n-=i*(i-1)*(i-2)/6;
				for(int j = i;j >= 2;j--){
					if(j*(j-1)/2<=n){
						ans++;
						for(int k = ans-j-1;k < ans-1;k++) a[k][ans-1] = a[ans-1][k] = 1;
						n -= j*(j-1)/2;
						for(int k = j+1;k >= 2;k--){
							if(k*(k-1)/2<=n){
								ans++;
								for(int b = ans-k-1;b < ans-1;b++) a[b][ans-1] = a[ans-1][b] = 1;
								n -= k*(k-1)/2;
								break;
							}
						}
						break;
					}
				}
				break;
			}
		}
	}
	cout << ans << "\n";
	for(int i = 0;i < ans;i++){
		for(int j = 0;j < ans;j++) cout << a[i][j];
		cout << "\n";
	}
}


#include<bits/stdc++.h>
#define ll long long int
using namespace std;
#define fio ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define endl "\n"
#define maxpq priority_queue<ll>
#define minpq priority_queue<ll, vector<ll>, greater<ll> >
#define vi vector<ll>
#define pii pair<ll, ll>
#define vii vector<pii>
#define for0(i, n) for (int i = 0; i < n; i++)
#define for1(i, n) for (int i = 1; i <= n; i++)
#define loop(i,a,b) for (int i = a; i < b; i++)
#define bloop(i,a,b) for (int i = a ; i>=b;i--)
#define MOD 1000000007
#define INT_MAXI 9000000000000000000
#define INT_MINI -9000000000000000000

ll max(ll a, ll b) {if (a > b) return a; else return b;}
ll min(ll a, ll b) {if (a < b) return a; else return b;}

const int dx[4] = { -1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
int XX[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
int YY[] = { -1, 0, 1, -1, 1, -1, 0, 1 };

vector<ll>vec[105];

int main()
{

	fio;

	ll x,i,j,a,b,c,n,k,y,z;

   cin>>k;

   vec[1].pb(2);
   vec[2].pb(1);
   vec[1].pb(3);
   vec[3].pb(1);
   vec[2].pb(3);
   vec[3].pb(2);

   k--;
   ll count=3,val=4,prev=1;
   while(k!=0&&val<=100)
   {

   	  ll flag=0;
   	  while(true)
   	  {

		  ll sum=(count*(count-1))/2;

   	  if(k>=sum)
   	  {
   	  	for(i=prev;i<val;i++)
   	  	{
   	  		vec[i].pb(val);
   	  		vec[val].pb(i);
			 }
			 k-=sum;
   	  	val++;
   	  	count++;

   	  	break;
		 }
		 count--;
		 prev++;

	}

   }
   cout<<val-1<<endl;

   for(i=1;i<=val-1;i++)
   {
   	   set<ll>s;
   	   for(j=0;j<vec[i].size();j++)
   	   s.insert(vec[i][j]);

   	   for(j=1;j<=val-1;j++)
   	   {
   	   	if(s.find(j)!=s.end())
   	   	cout<<"1";
   	   	else
   	   	cout<<"0";
		  }
		  cout<<endl;

   }

}


#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <stack>
#include <queue>
#include <array>
#include <bitset>
#include <cstdio>
#include <string>
#include <vector>
#include <random>
#include <chrono>
#include <utility>
#include <numeric>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <sstream>
#include <assert.h>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <functional>
#include <unordered_map>

using namespace std;
struct _ { ios_base::Init i; _() { ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); } } _;

#define ff first
#define ss second

int main() {

	int k; cin >> k;
	vector<pair<int, int>> ed;

	int cyc = 0, n = -1, st = 1;
	for (int i = 2; i <= 101; i++) {
		n = i;
		for (int j = i - 1; j >= st; j--) {
			if ((cyc + (i - j - 1)) > k) {
				st = i;
				break;
			}

			cyc += (i - j - 1);
			ed.push_back({j, i});
		}
		if (cyc >= k) break;
	}

	assert(cyc == k);
	vector<vector<int>> gr(n, vector<int>(n, 0));
	for (auto p : ed) {
		gr[p.ff - 1][p.ss - 1] = 1;
		gr[p.ss - 1][p.ff - 1] = 1;
	}
	cout << n << "\n";
	for (int i = 0; i <= n - 1; i++) {
		for (int j = 0; j <= n - 1; j++) cout << gr[i][j];
		cout << "\n";
	}

	return 0;
}


#include <bits/stdc++.h>

using matrix = std::array<std::bitset<100>, 100>;

int nchoose3(int n)
{
  return n*(n-1)*(n-2)/6;
}

matrix gen_complete(int n)
{
  matrix A{};
  for (int i = 0; i < n; i++)
    for (int j = i+1; j < n; j++)
    {
      A[i].set(j);
      A[j].set(i);
    }

  return A;
}

void print(const matrix& A, int n)
{
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < n; j++)
      std::cout << (A[i].test(j) ? '1' : '0');

    std::cout << '\n';
  }
}

int main()
{
  int k;
  std::cin >> k;

  int n = 3;
  while (nchoose3(n) < k) n++;
  if (k == nchoose3(n))
  {
    std::cout << n << '\n';
    matrix A = gen_complete(n);
    print(A, n);
    return 0;
  }

  matrix A{};
  int num_cycles = 0;
  // Add cycle (m-2)-(m-1)-m
  for (int m = 2; m <= n-1; m++)
  {
    A[m-2].set(m-1);
    A[m-1].set(m-2);

    A[m-2].set(m);
    A[m].set(m-2);

    A[m-1].set(m);
    A[m].set(m-1);

    num_cycles++;
  }

  if (num_cycles == k)
  {
    std::cout << n << '\n';
    print(A, n);
    return 0;
  }

  do
  {
    for (int n1 = 0; n1 < n; n1++)
      for (int n2 = n1+1; n2 < n; n2++)
      {
        if (A[n1].test(n2)) continue;

        int new_potential_cycles = 0;
        for (int i = 0; i < n; i++)
          new_potential_cycles += (A[n1].test(i) && A[n2].test(i));

        if (new_potential_cycles + num_cycles > k) continue;

        num_cycles += new_potential_cycles;
        A[n1].set(n2);
        A[n2].set(n1);
      }

    if (num_cycles == k) break;

    assert(num_cycles < k);
    A[n-2].set(n-1);
    A[n-1].set(n-2);

    A[n-2].set(n);
    A[n].set(n-2);

    A[n-1].set(n);
    A[n].set(n-1);

    num_cycles++;
    n++;
    assert(n <= 100);
  } while (num_cycles < k);

  std::cout << n << '\n';
  print(A, n);
}


#include<bits/stdc++.h>
using namespace std;

const int N = 111;
int a[N][N];
int extra_node = 0;

int main()
{
	int k;
	cin >> k;
	int nodes = -1;
	for(int i = 100; i >= 3; --i)
	{
		long long cur = i * (i - 1) * (i - 2);
		cur /= 6;
		if(cur <= k)
		{
			nodes = i;
			break;
		}
	}
	extra_node = nodes;
	k -= (nodes * (nodes - 1) * (nodes - 2))/6;
	for(int i = 1; i <= nodes; i++)
	{
		for(int j = 1; j <= nodes; j++)
		{
			if(i == j)continue;
			a[i][j] = 1;
		}
	}

	while(k > 0)
	{
		int yes = -1;
		for(int i = 2; i <= nodes; i++)
		{
			long long cur = i * (i -1);
			cur /= 2;
			if(cur <= k)yes = i;
		}
		++extra_node;
		k -= (yes * (yes - 1))/2;
		for(int i = 1; i <= yes; i++)
		{
			a[i][extra_node] = a[extra_node][i] = 1;
		}
	}

	cout << extra_node << endl;

	for(int i = 1; i <= extra_node; i++)
	{
		for(int j = 1; j <= extra_node; j++)
		{
			cout << a[i][j];
		}cout << endl;
	}
}


//	The mountains of Hakone are?
//		the steepest in the World!

#include<bits/stdc++.h>
using namespace std;

int n;
vector<int> v;
string ans[110];

void add_Edge(int x, int y){
	ans[x][y]='1';
	ans[y][x]='1';
}

int main(){

	// scanf("%d",&n);
	// for(int i=3;i<=100;i++){
	// 	int cur = (i*(i-1)*(i-2))/6;
	// 	s.insert(cur);
	// 	mp[cur] = i;
	// }
	// //for(int i = 1;i<=100000;i++){
	// //int n = i;
	// int ret = 0;
	// while(n>0){
	// 	auto it = s.upper_bound(n);
	// 	it--;
	// 	cout << mp[(*it)] << endl;
	// 	n-= (*it);
	// 	ret+= mp[(*it)];
	// }
	// if(ret>=100){
	// //	cout << i << " " << ret << endl;
	// //	break;
	// //}
	// //assert(ret<=100);
	// }

	scanf("%d",&n);
	int Kn = 3;
	for(int i=100;i>=1;i--){
		int cur = (i*(i-1)*(i-2))/6;
		if(cur<=n){
			n-=cur;
			Kn = i;
			break;
		}
	}
	while(n>0){
		for(int i=Kn;i>=0;i--){
			int cur = (i*(i-1))/2;
			if(cur<=n){
				n-=cur;
				v.push_back(i);
				break;
			}
		}
	}
	int N = Kn+v.size();
	for(int i=0;i<N;i++){
		for(int j=0;j<N;j++){
			ans[i]+='0';
		}
	}
	for(int i=0;i<Kn;i++){
		for(int j=0;j<i;j++){
			add_Edge(i,j);
		}
	}
	for(int i=0;i<v.size();i++){
		for(int j=0;j<v[i];j++){
			add_Edge(Kn+i,j);
		}
	}

	printf("%d\n",N);
	for(int i=0;i<N;i++){
		cout << ans[i] << endl;
	}

return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define f(i,a,b) for( int i = a; i < b ; i++ )
#define af(i,a,b) for( int i = a; i >= b ; i--)
#define rep(i,a,b,k) for(int i = a; i < b ; i+= k )
#define arep(i,a,b,k) for( int i = a; i >= b ; i-= k)
#define fs first
#define sc second
#define pb push_back
#define mp make_pair
#define sor(a) sort( a.begin(), a.end() )
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)

typedef long double ld;
typedef long long int ll;
typedef vector<int> vi ;
typedef pair<int,int> ii ;
typedef vector<ii> vii ;

const int MAX= 1000001;

int t[110][110];
int main(){
	fastio;
	int n,k;
	cin>>k;
	f(i,2,k+2){
		n=i;
		if((i+1)*i*(i-1)/6>k) break;
	}
	f(i,1,n+1) f(j,1,n+1) if(i!=j) t[i][j]=1;
	int c =  n*(n-1)*(n-2)/6;
	k-=c;
	c=n+1;
	while(k>0){
		int aux;
		f(i,1,k+2){
			aux=i;
			if((i+1)*i/2>k) break;
		}
		f(i,1,aux+1) t[c][i]=t[i][c]=1;
		k-=(aux*(aux-1)/2);
		c++;
	}
	f(i,1,c){
		f(j,1,c) cout<<t[i][j];
		cout<<endl;
	}
}


#include <bits/stdc++.h>
using namespace std;
#define f(i,a,b) for( int i = a; i < b ; i++ )
#define af(i,a,b) for( int i = a; i >= b ; i--)
#define rep(i,a,b,k) for(int i = a; i < b ; i+= k )
#define arep(i,a,b,k) for( int i = a; i >= b ; i-= k)
#define fs first
#define sc second
#define pb push_back
#define mp make_pair
#define sor(a) sort( a.begin(), a.end() )
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)

typedef long double ld;
typedef long long int ll;
typedef vector<int> vi ;
typedef pair<int,int> ii ;
typedef vector<ii> vii ;

const int MAX= 1000001;

int t[110][110];
int main(){
	fastio;
	int n,k;
	cin>>k;
	f(i,2,k+2){
		n=i;
		if((i+1)*i*(i-1)/6>k) break;
	}
	f(i,1,n+1) f(j,1,n+1) if(i!=j) t[i][j]=1;
	int c =  n*(n-1)*(n-2)/6;
	k-=c;
	c=n+1;
	while(k>0){
		int aux;
		f(i,1,k+2){
			aux=i;
			if((i+1)*i/2>k) break;
		}
		f(i,1,aux+1) t[c][i]=t[i][c]=1;
		k-=(aux*(aux-1)/2);
		c++;
	}
	cout<<c-1<<endl;
	f(i,1,c){
		f(j,1,c) cout<<t[i][j];
		cout<<endl;
	}
}


#include<bits/stdc++.h>
#define int long long
using namespace std;

int32_t main(){
    vector<int> k2table(101);
    vector<int> k3table(101);
    for(int i = 2; i <= 100; i++){
        k2table[i] = i*(i-1)/2;
    }
    for(int i = 3; i <= 100; i++){
        k3table[i] = i*(i-1)*(i-2)/6;
    }
    int k;
    cin >> k;
    int graphSize = 0;
    int leftEdge = k;
    for(int i = 3; i <= 100; i++) {
        if (k3table[i] > k) {
            graphSize = i - 1;
            break;
        }
    }
    vector<vector<int>> graph(100+1, vector<int>(100+1));
    for(int i = 1; i <= graphSize; i++){
        for(int j = 1; j <= graphSize; j++){
            if(i == j) continue;
            graph[i][j] = 1;
        }
    }
    leftEdge -= k3table[graphSize];
    graphSize++;
    while(leftEdge > 0) {
        int edgeSize = 0;
        for (int i = 2; i <= 100; i++) {
            if (k2table[i] > leftEdge) {
                leftEdge -= k2table[i - 1];
                edgeSize = k2table[i - 1];
                break;
            }
        }
        for (int i = 1; i <= edgeSize; i++) {
            graph[graphSize][i] = 1;
            graph[i][graphSize] = 1;
        }
        graphSize++;
    }
    cout << graphSize-1 << endl;
    for(int i = 1; i < graphSize; i++){
        for(int j = 1; j < graphSize; j++){
            cout << graph[i][j];
        }
        cout << endl;
    }
}


#include<bits/stdc++.h>
#define int long long
using namespace std;

int32_t main(){
    vector<int> k2table(101);
    vector<int> k3table(101);
    for(int i = 2; i <= 100; i++){
        k2table[i] = i*(i-1)/2;
    }
    for(int i = 3; i <= 100; i++){
        k3table[i] = i*(i-1)*(i-2)/6;
    }
    int k;
    cin >> k;
    int graphSize = 0;
    int leftEdge = k;
    for(int i = 3; i <= 100; i++) {
        if (k3table[i] > k) {
            graphSize = i - 1;
            break;
        }
    }
    vector<vector<int>> graph(100+1, vector<int>(100+1));
    for(int i = 1; i <= graphSize; i++){
        for(int j = 1; j <= graphSize; j++){
            if(i == j) continue;
            graph[i][j] = 1;
        }
    }
    leftEdge -= k3table[graphSize];
    graphSize++;
    while(leftEdge > 0) {
        int edgeSize = 0;
        for (int i = 2; i <= 100; i++) {
            if (k2table[i] > leftEdge) {
                leftEdge -= k2table[i - 1];
                edgeSize = i-1;
                break;
            }
        }
        for (int i = 1; i <= edgeSize; i++) {
            graph[graphSize][i] = 1;
            graph[i][graphSize] = 1;
        }
        graphSize++;
    }
    cout << graphSize-1 << endl;
    for(int i = 1; i < graphSize; i++){
        for(int j = 1; j < graphSize; j++){
            cout << graph[i][j];
        }
        cout << endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
#define pi 3.14159265359
#define int long long
#define pii pair<int,int>
const int mod=1e9+7;

int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};

int32_t  main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);

  #ifndef ONLINE_JUDGE
  freopen("input.txt","rt",stdin);
  freopen("output.txt","wt",stdout);
  #endif

vector<vector<int>>vis(101,vector<int>(101,0));

int k;
cin>>k;

if(k==1)
{
  cout<<3<<"\n";
  cout<<"011\n101\n110\n"; return 0;
}

int num=0;
while(num*(num-1)*(num-2)/6<=k)
{
  num++;
}

num--;
k-=(num*(num-1)*(num-2))/6;
int ans=num;

for(int i=1;i<=num;i++)
{
  for(int j=i+1;j<=num;j++)
  vis[i][j]=vis[j][i]=1;
}

while(k)
{
  ans++;
  for(int j=1;j<ans;j++)
  {
    for(int i=j+1;i<ans;i++)
    {
       if(!k)break;
       k--;
       vis[i][ans]=vis[j][ans]=1;
    }
  }

}

cout<<ans<<"\n";
for(int i=1;i<=ans;i++)
{
  for(int j=1;j<=ans;j++)
  {
    cout<<vis[i][j];
  }
  cout<<"\n";
}

}


#include<bits/stdc++.h>
using namespace std;
#define pi 3.14159265359
#define int long long
#define pii pair<int,int>
const int mod=1e9+7;

int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};

int32_t  main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);

  #ifndef ONLINE_JUDGE
  freopen("input.txt","rt",stdin);
  freopen("output.txt","wt",stdout);
  #endif

vector<vector<int>>vis(101,vector<int>(101,0));

int k;
cin>>k;

if(k==1)
{
  cout<<3<<"\n";
  cout<<"011\n101\n110\n"; return 0;
}

int num=0;
while(num*(num-1)*(num-2)/6<=k)
{
  num++;
}

num--;
k-=(num*(num-1)*(num-2))/6;
int ans=num;

for(int i=1;i<=num;i++)
{
  for(int j=i+1;j<=num;j++)
  vis[i][j]=vis[j][i]=1;
}

while(k)
{
  ans++;

  num=2;
  while( num *(num-1) /2 <=k)
  num++;

  num--;

  k-=num*(num-1)/2;
  for(int i=1;i<=num;i++)
  {
    vis[i][ans]=vis[ans][i]=1;
  }

}

cout<<ans<<"\n";
for(int i=1;i<=ans;i++)
{
  for(int j=1;j<=ans;j++)
  {
    cout<<vis[i][j];
  }
  cout<<"\n";
}

}


#include<bits/stdc++.h>
using namespace std;
#define pi 3.14159265359
#define int long long
#define pii pair<int,int>
const int mod=1e9+7;

int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};

int32_t  main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);

  #ifndef ONLINE_JUDGE
  freopen("input.txt","rt",stdin);
  freopen("output.txt","wt",stdout);
  #endif

vector<vector<int>>vis(101,vector<int>(101,0));

int k;
cin>>k;

if(k==1)
{
  cout<<3;
  cout<<"011\n101\n110\n"; return 0;
}

int num=0;
while(num*(num-1)*(num-2)/6<=k)
{
  num++;
}

num--;
k-=(num*(num-1)*(num-2))/6;
int ans=num;

for(int i=1;i<=num;i++)
{
  for(int j=i+1;j<=num;j++)
  vis[i][j]=vis[j][i]=1;
}

while(k)
{
  ans++;
  num=2;
  while(num*(num-1)<=2*k)
  num++;

  num--;
  k-=(num)*(num-1)/2;
  for(int i=1;i<=num;i++)
  {
    vis[i][ans]=1;
    vis[ans][i]=1;
  }

}

cout<<ans<<"\n";
for(int i=1;i<=ans;i++)
{
  for(int j=1;j<=ans;j++)
  {
    cout<<vis[i][j];
  }
  cout<<"\n";
}

}


#include<bits/stdc++.h>
using namespace std;
#define pi 3.14159265359
#define int long long
#define pii pair<int,int>
const int mod=1e9+7;

int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};

int32_t  main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);

  #ifndef ONLINE_JUDGE
  freopen("input.txt","rt",stdin);
  freopen("output.txt","wt",stdout);
  #endif

vector<vector<int>>vis(101,vector<int>(101,0));

int k;
cin>>k;

if(k==1)
{
  cout<<3<<"\n";
  cout<<"011\n101\n110\n"; return 0;
}

int num=0;
while(num*(num-1)*(num-2)/6<=k)
{
  num++;
}

num--;
k-=(num*(num-1)*(num-2))/6;
int ans=num;

for(int i=1;i<=num;i++)
{
  for(int j=i+1;j<=num;j++)
  vis[i][j]=vis[j][i]=1;
}

while(k)
{
  ans++;
  for(int j=1;j<ans;j++)
  {
    for(int i=j+1;i<ans;i++)
    {
       if(!k)break;
       k--;
       vis[i][ans]=vis[j][ans]=1; vis[ans][i]=vis[ans][j]=1;
    }
  }

}

cout<<ans<<"\n";
for(int i=1;i<=ans;i++)
{
  for(int j=1;j<=ans;j++)
  {
    cout<<vis[i][j];
  }
  cout<<"\n";
}

}


#include <bits/stdc++.h>

using namespace std;

const int N_MAX = 1002;

int k;

int c3[N_MAX];
int c2[N_MAX];

bool ma[N_MAX][N_MAX];

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> k;
    for(int i = 3; i <= 100; i++)
        c3[i] = i * (i - 1) * (i - 2) / 6;
    for(int i = 2; i <= 100; i++)
        c2[i] = i * (i - 1) / 2;
    int pos3 = 100;
    int cnt = 0;
    while(k > 0)
    {
        while(k < c3[pos3])
            pos3--;
        for(int i = cnt + 1; i <= cnt + pos3; i++)
            for(int j = cnt + 1; j <= cnt + pos3; j++)
                ma[i][j] = (i != j);
        int aux = cnt;
        cnt += pos3;
        k -= c3[pos3];
        int pos2 = pos3;
        while(k > 0)
        {
            while(pos2 > 2 && k < c2[pos2])
                pos2--;
            if(k < c2[pos2])
                break;
            cnt++;
            k -= c2[pos2];
            for(int i = aux + 1; i <= aux + pos2; i++)
                ma[i][cnt] = ma[cnt][i] = true;
        }
    }
    cout << cnt << "\n";
    for(int i = 1; i <= cnt; i++, cout << "\n")
        for(int j = 1; j <= cnt; j++)
            cout << ma[i][j];
    return 0;
}


#include <bits/stdc++.h>
#define watch(x) std::cout << "$ LINE @" << __LINE__ << " FUNC @" << __FUNCTION__ << "\n$ " \
                           << (#x) << ": " << x << std::endl

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

template <typename Tp>
inline void read(Tp &x)
{
    static char c;
    static bool neg;
    x = 0, c = getchar(), neg = false;
    for (; !isdigit(c); c = getchar())
    {
        if (c == '-')
        {
            neg = true;
        }
    }
    for (; isdigit(c); c = getchar())
    {
        x = x * 10 + c - '0';
    }
    if (neg)
    {
        x = -x;
    }
}

const int N = 100 + 5;

int k, n, t;

inline int C(int n, int m)
{
    if (m == 2)
    {
        return n * (n - 1) / 2;
    }
    else if (m == 3)
    {
        return n * (n - 1) * (n - 2) / 6;
    }
    else
    {
        return -1;
    }
}

int G[N][N];

int main()
{
    read(k);
    for (; C(n, 3) <= k; ++n)
        ;
    --n;
    k -= C(n, 3);
    for (int i = 1; i <= n; ++i)
    {
        for (int j = i + 1; j <= n; ++j)
        {
            G[i][j] = G[j][i] = 1;
        }
    }
    while (k > 0)
    {
        ++n;
        for (t = 0; C(t, 2) <= k; ++t)
            ;
        --t;
        for (int i = 1; i <= t; ++i)
        {
            G[i][n] = G[n][i] = 1;
        }
        k -= C(t, 2);
    }
    printf("%d\n", n);
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= n; ++j)
        {
            putchar('0' + G[i][j]);
        }
        puts("");
    }
}


#include <bits/stdc++.h>
#define watch(x) std::cout << "$ LINE @" << __LINE__ << " FUNC @" << __FUNCTION__ << "\n$ " \
                           << (#x) << ": " << x << std::endl

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

template <typename Tp>
inline void read(Tp &x)
{
    static char c;
    static bool neg;
    x = 0, c = getchar(), neg = false;
    for (; !isdigit(c); c = getchar())
    {
        if (c == '-')
        {
            neg = true;
        }
    }
    for (; isdigit(c); c = getchar())
    {
        x = x * 10 + c - '0';
    }
    if (neg)
    {
        x = -x;
    }
}

const int N = 100 + 5;

int k, n = 0;
int mp[N][N];

inline int C(int n, int m)
{
    if (m == 2)
    {
        return n * (n - 1) / 2;
    }
    else if (m == 3)
    {
        return n * (n - 1) * (n - 2) / 6;
    }
    else
    {
        return -1;
    }
}

int main()
{
    read(k);
    for (; C(n, 3) <= k; ++n)
        ;
    --n;
    for (int i = 1; i <= n; ++i)
    {
        for (int j = i + 1; j <= n; ++j)
        {
            mp[i][j] = mp[j][i] = 1;
        }
    }
    k -= C(n, 3);
    while (k > 0)
    {
        int t = 0;
        for (; C(t, 2) <= k; ++t)
            ;
        --t;
        ++n;
        for (int i = 1; i <= t; ++i)
        {
            mp[n][i] = mp[i][n] = 1;
        }
        k -= C(t, 2);
    }
    printf("%d\n", n);
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= n; ++j)
        {
            putchar('0' + mp[i][j]);
        }
        puts("");
    }
}


#include <bits/stdc++.h>
#define watch(x) std::cout << "$ LINE @" << __LINE__ << " FUNC @" << __FUNCTION__ << "\n$ " \
                           << (#x) << ": " << x << std::endl

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

template <typename Tp>
inline void read(Tp &x)
{
    static char c;
    static bool neg;
    x = 0, c = getchar(), neg = false;
    for (; !isdigit(c); c = getchar())
    {
        if (c == '-')
        {
            neg = true;
        }
    }
    for (; isdigit(c); c = getchar())
    {
        x = x * 10 + c - '0';
    }
    if (neg)
    {
        x = -x;
    }
}

const int N = 100000 + 5;

int n, m;
int b[N], g[N];

namespace BIT
{
#define lowbit(x) ((x) & -(x))
    int t[N];
    inline void add(int x, int val)
    {
        for (; x < N; x += lowbit(x))
        {
            t[x] += val;
        }
    }
    inline int query(int x)
    {
        int res = 0;
        for (; x > 0; x -= lowbit(x))
        {
            res += t[x];
        }
        return res;
    }
#undef lowbit
} // namespace BIT

int main()
{
    read(n), read(m);
    for (int i = 1; i <= n; ++i)
    {
        read(b[i]);
    }
    sort(b + 1, b + n + 1);
    for (int i = 1; i <= m; ++i)
    {
        read(g[i]);
    }
    sort(g + 1, g + m + 1);
    if (g[1] < b[n])
    {
        puts("-1");
    }
    else if (g[1] == b[n])
    {
        ll ans = 0;
        for (int i = 1; i <= n - 1; ++i)
        {
            ans += (ll)b[i] * m;
        }
        for (int i = 1; i <= m; ++i)
        {
            ans += g[i];
        }
        printf("%lld\n", ans);
    }
    else
    {
        ll ans = 0;
        for (int i = 1; i <= n - 1; ++i)
        {
            ans += (ll)b[i] * m;
        }
        for (int i = 1; i <= m - 1; ++i)
        {
            ans += g[i];
        }
        ans -= b[n - 1];
        ans += g[m];
        ans += b[n];
        printf("%lld\n", ans);
    }
    return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
using namespace std;
#define ll  long long
#define PI  acos(-1)
#define pb  push_back
#define ins insert
#define INF 9000000000000000007 //1e18+7
#define mk  make_pair
#define lb(v,x) lower_bound(all(v),x)
#define ub(v,x)  upper_bound(all(v),x)
#define ff  first
#define ss  second
#define rev reverse
#define endl "\n"
#define max3(x,y,z)  max(x,max(y,z))
#define min3(x,y,z)  min(x,min(y,z))
#define sz(a) (ll)a.size()
#define double long double
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define mset(x,y)  memset(x,y,sizeof(x))
#define all(x)   (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define bp(n)  __builtin_popcountll(n)
#define mxt(a)  *(max_element(a.begin(),a.end()))
#define mnt(a)  *(min_element(a.begin(),a.end()))
#define unique_sort(c) (sort(all(c)), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define rep(i,a,b) for(ll i=(a);i<=(b);++i)
#define trav(a, x) 	  for(auto &a : x)
#define re(i,n)       for(ll i=0;i<n;++i)
#define int2Bin(x,y)  bitset <y> z=x; cout<<z.to_string()<<endl;
const double eps=1e-7;
const string alpha = "abcdefghijklmnopqrstuvwxyz";
// int dx[8]={+1, +1, +1, 0, 0, -1, -1, -1};
// int dy[8]={+1, 0, -1, +1, -1, +1, 0, -1};
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
ll power(ll x,ll y){ll ans=1;x=x;while(y>0){if(y&1)ans=(ans*x);y=y>>1;x=(x*x);}return ans;}
ll sqr(ll x) { return x * x;}
template <typename T> T gcd(T a,T b){ if(a==0) return b; return gcd(b%a,a); }
template <class T> inline void chmax(T &x,T y){ x = max((x), (y));}
template <class T> inline void chmin(T &x,T y){ x = min((x), (y));}
template <class T> T abs(T x) { return x>0 ? x : -x;}
template <typename T> T powm(T a,T b, ll m){T cnt=1; while(b>0){ if(b%2==1) cnt=(cnt*a)%m; b/=2; a=(a*a)%m; }return cnt%m;}
typedef pair<int,int>  pii;
typedef pair<ll,ll>  pll;
typedef vector<pll>  vpll;
typedef vector<pii>  vpii;
typedef vector<ll>   vll;
typedef vector<int>  vii;
#define minpq priority_queue<T,vector<T>,greater<T> >;
//#define T pll
//#define ordered_set tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>
//*X.find_by_order(k) returns the kth largest element (0-based).
//X.order_of_key(val) returns the no. of values less than val.
ll ncr(ll n,ll r){ll ans=1;if(r>n)return 0;if(r>n-r)r=n-r;for(ll i=0;i<r;i++){ans*=(n-i);ans/=(i+1);}return ans;}
const int MOD=1000000007;
const int N=300005;
void prec(){

}
int a[104][104];
void run(){
    int n;cin>>n;
    int ans=0,tot=0;
    for(int i=3;i<=100;i++){
        if(ncr(i,3)<=n)
            tot=i;
    }
    ans=tot;
    n-=ncr(tot,3);
    for(int i=1;i<=tot;i++){
        for(int j=1;j<=tot;j++){
            if(i!=j)
                a[i][j]=1;
        }
    }
    while(n){
        int sec=0;
        for(int i=2;i<=tot;i++)
        {
            if(ncr(i,2)<=n){
                sec=i;
            }
        }
        n-=ncr(sec,2);
        ans++;
        for(int i=1;i<=sec;i++)
            a[i][ans]=a[ans][i]=1;
    }
    cout<<ans<<endl;
    for(int i=1;i<=ans;i++){
        for(int j=1;j<=ans;j++){
            cout<<a[i][j];
        }
        cout<<endl;
    }
}
int32_t main()
{
    cin.sync_with_stdio(0);cin.tie(0);
	cin.exceptions(cin.failbit);
    int tc=1;
    //cin>>tc;
    prec();
    re(i,tc)
    	run();
    return 0;
}
/*
	stuff you should look for
	* int overflow,array bounds.
	* special cases (n=1?).
	* N,MOD value.
*/