Problem:
Problem C:
Shopping
Your friend will enjoy shopping. She will walk through a mall along a straight street, where $N$ individual shops (numbered from 1 to $N$) are aligned at regular intervals. Each shop has one door and is located at the one side of the street. The distances between the doors of the adjacent shops are the same length, i.e. a unit length. Starting shopping at the entrance of the mall, she visits shops in order to purchase goods. She has to go to the exit of the mall after shopping.
She requires some restrictions on visiting order of shops. Each of the restrictions indicates that she shall visit a shop before visiting another shop. For example, when she wants to buy a nice dress before choosing heels, she shall visit a boutique before visiting a shoe store. When the boutique is farther than the shoe store, she must pass the shoe store before visiting the boutique, and go back to the shoe store after visiting the boutique.
If only the order of the visiting shops satisfies all the restrictions, she can visit other shops in any order she likes.
Write a program to determine the minimum required walking length for her to move from the entrance to the exit.
Assume that the position of the door of the shop numbered $k$ is $k$ units far from the entrance, where the position of the exit is $N + 1$ units far from the entrance.
Input
The input consists of a single test case.
$N$ $m$
$c_1$ $d_1$
.
.
.
$c_m$ $d_m$
The first line contains two integers $N$ and $m$, where $N$ ($1 \leq N \leq 1000$) is the number of shops, and $m$ ($0 \leq m \leq 500$) is the number of restrictions. Each of the next $m$ lines contains two integers $c_i$ and $d_i$ ($1 \leq c_i < d_i \leq N$) indicating the $i$-th restriction on the visiting order, where she must visit the shop numbered $c_i$ after she visits the shop numbered $d_i$ ($i = 1, . . . , m$).
There are no pair of $j$ and $k$ that satisfy $c_j = c_k$ and $d_j = d_k$.
Output
Output the minimum required walking length for her to move from the entrance to the exit. You should omit the length of her walk in the insides of shops.
Sample Input 1
10 3
3 7
8 9
2 5
Sample Output 1
23
Sample Input 2
10 3
8 9
6 7
2 4
Sample Output 2
19
Sample Input 3
10 0
Sample Output 3
11
Sample Input 4
10 6
6 7
4 5
2 5
6 9
3 5
6 8
Sample Output 4
23
Sample Input 5
1000 8
3 4
6 1000
5 1000
7 1000
8 1000
4 1000
9 1000
1 2
Sample Output 5
2997

Submitted solutions:

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <numeric>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <sstream>
#include <complex>
#include <fstream>
#include <bitset>
#include <time.h>
#include <tuple>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;

#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e12;
const ll MOD = 1e9 + 7;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,N) for(int i=0;i<(N);i++)
#define ALL(s) (s).begin(),(s).end()
#define EQ(a,b) (abs((a)-(b))<EPS)
#define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) )
#define fi first
#define se second
#define N_SIZE (1LL << 20)
#define NIL -1

ll sq(ll num) { return num*num; }
ll mod_pow(ll x, ll n) {
	if (n == 0)return 1;
	if (n == 1)return x%MOD;
	ll res = sq(mod_pow(x, n / 2));
	res %= MOD;
	if (n % 2 == 1) {
		res *= x;
		res %= MOD;
	}
	return res;
}
ll mod_add(ll a, ll b) { return (a + b) % MOD; }
ll mod_sub(ll a, ll b) { return (a - b + MOD) % MOD; }
ll mod_mul(ll a, ll b) { return a*b % MOD; }

//dp
int n, m;
vector<P> vp2;
ll dp[510][1100];

int main() {
	cin >> n >> m;
	if (m == 0) {
		cout << n + 1 << endl;
		return 0;
	}
	rep(i, m) {
		ll c, d;
		cin >> c >> d;
		vp2.push_back({ c,d });
	}
	sort(ALL(vp2));
	rep(i, 510)rep(j, 1010)dp[i][j] = INF;
	dp[0][0] = 0;
	int now = 0;
	rep(i, vp2.size()) {
		ll ci = vp2[i].first;
		ll di = vp2[i].second;
		FOR(j, di, n + 2) {//新しく経由する点
			FOR(k, now, n + 2) {//今までに経由した点
				if (k < j)dp[i + 1][j] = min(dp[i + 1][j], dp[i][k] + (j - now) + (j - ci));
				else dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + (ci - now));
			}
		}
		now = ci;
	}
	ll ans = INF;
	rep(i, n + 2) {
		ans = min(dp[vp2.size()][i] + n + 1 - now, ans);
	}
	cout << ans << endl;
}

//int n, m;
//vector<P> vp;
//int sum[100100];
//
//int main() {
//	cin >> n >> m;
//	vp.resize(m);
//	rep(i, m) {
//		int a, b;
//		cin >> a >> b;
//		sum[a]++;
//		sum[b]--;
//	}
//	rep(i, n + 2)sum[i + 1] += sum[i];
//	ll ans = 0;
//	rep(i, n + 1) {
//		if (sum[i] > 0)ans += 3;
//		else ans++;
//	}
//	cout << ans << endl;
//}
accuracy: 1
time_ms: 460
memory_kb: 7516
final_rank: 3

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <numeric>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <sstream>
#include <complex>
#include <fstream>
#include <bitset>
#include <time.h>
#include <tuple>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;

#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e12;
const ll MOD = 1e9 + 7;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,N) for(int i=0;i<(N);i++)
#define ALL(s) (s).begin(),(s).end()
#define EQ(a,b) (abs((a)-(b))<EPS)
#define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) )
#define fi first
#define se second
#define N_SIZE (1LL << 20)
#define NIL -1

ll sq(ll num) { return num*num; }
ll mod_pow(ll x, ll n) {
	if (n == 0)return 1;
	if (n == 1)return x%MOD;
	ll res = sq(mod_pow(x, n / 2));
	res %= MOD;
	if (n % 2 == 1) {
		res *= x;
		res %= MOD;
	}
	return res;
}
ll mod_add(ll a, ll b) { return (a + b) % MOD; }
ll mod_sub(ll a, ll b) { return (a - b + MOD) % MOD; }
ll mod_mul(ll a, ll b) { return a*b % MOD; }

//dp
int n, m;
vector<P> vp;
ll dp[510][1100];

int main() {
	cin >> n >> m;
	if (m == 0) {
		cout << n + 1 << endl;
		return 0;
	}
	rep(i, m) {
		ll c, d;
		cin >> c >> d;
		vp.push_back({ c,d });
	}
	sort(ALL(vp));
	vector<P> vp2;
	ll d = -1;
	rep(i, vp.size()) {
		//if (d < vp[i].second) {
		//	d = vp[i].second;
			vp2.push_back(vp[i]);
		//}
	}
	rep(i, 510)rep(j, 1010)dp[i][j] = INF;
	dp[0][0] = 0;
	int now = 0;
	rep(i, vp2.size()) {
		ll ci = vp2[i].first;
		ll di = vp2[i].second;
		FOR(j, di, n + 2) {//新しく経由する点
			FOR(k, now, n + 2) {//今までに経由した点
				if (k < j)dp[i + 1][j] = min(dp[i + 1][j], dp[i][k] + (j - now) + (j - ci));
				else dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + (ci - now));
			}
		}
		now = ci;
	}
	//FOR(i, 1, m + 1) {
	//	if (dp[i][5] == INF) {
	//		cout << i << endl;
	//		break;
	//	}
	//}
	//rep(i, vp2.size() + 1) {
	//	if (i != vp2.size())continue;
	//	rep(j, n + 1) {
	//		if (dp[i][j] != INF)printf("%4d", dp[i][j]);
	//		else cout << " INF";
	//	}
	//	cout << endl;
	//}
	ll ans = INF;
	rep(i, n + 2) {
		ans = min(dp[vp2.size()][i] + n + 1 - now, ans);
	}
	cout << ans << endl;
	//cout << dp[vp2.size()][d] + n + 1 - now << endl;
}

//int n, m;
//vector<P> vp;
//int sum[100100];
//
//int main() {
//	cin >> n >> m;
//	vp.resize(m);
//	rep(i, m) {
//		int a, b;
//		cin >> a >> b;
//		sum[a]++;
//		sum[b]--;
//	}
//	rep(i, n + 2)sum[i + 1] += sum[i];
//	ll ans = 0;
//	rep(i, n + 1) {
//		if (sum[i] > 0)ans += 3;
//		else ans++;
//	}
//	cout << ans << endl;
//}
accuracy: 1
time_ms: 460
memory_kb: 7532
final_rank: 4

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <numeric>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <sstream>
#include <complex>
#include <fstream>
#include <bitset>
#include <time.h>
#include <tuple>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;

#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e12;
const ll MOD = 1e9 + 7;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,N) for(int i=0;i<(N);i++)
#define ALL(s) (s).begin(),(s).end()
#define EQ(a,b) (abs((a)-(b))<EPS)
#define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) )
#define fi first
#define se second
#define N_SIZE (1LL << 20)
#define NIL -1

ll sq(ll num) { return num*num; }
ll mod_pow(ll x, ll n) {
	if (n == 0)return 1;
	if (n == 1)return x%MOD;
	ll res = sq(mod_pow(x, n / 2));
	res %= MOD;
	if (n % 2 == 1) {
		res *= x;
		res %= MOD;
	}
	return res;
}
ll mod_add(ll a, ll b) { return (a + b) % MOD; }
ll mod_sub(ll a, ll b) { return (a - b + MOD) % MOD; }
ll mod_mul(ll a, ll b) { return a*b % MOD; }

//dp
int n, m;
vector<P> vp;
ll dp[510][1100];

int main() {
	cin >> n >> m;
	if (m == 0) {
		cout << n + 1 << endl;
		return 0;
	}
	rep(i, m) {
		ll c, d;
		cin >> c >> d;
		vp.push_back({ c,d });
	}
	sort(ALL(vp));
	vector<P> vp2;
	ll d = -1;
	rep(i, vp.size()) {
		if (d < vp[i].second) {
			d = vp[i].second;
			vp2.push_back(vp[i]);
		}
	}
	rep(i, 510)rep(j, 1010)dp[i][j] = INF;
	dp[0][0] = 0;
	int now = 0;
	rep(i, vp2.size()) {
		ll ci = vp2[i].first;
		ll di = vp2[i].second;
		FOR(j, di, n + 2) {//新しく経由する点
			FOR(k, now, n + 2) {//今までに経由した点
				if (k < j)dp[i + 1][j] = min(dp[i + 1][j], dp[i][k] + (j - now) + (j - ci));
				else dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + (ci - now));
			}
		}
		now = ci;
	}
	//FOR(i, 1, m + 1) {
	//	if (dp[i][5] == INF) {
	//		cout << i << endl;
	//		break;
	//	}
	//}
	//rep(i, vp2.size() + 1) {
	//	if (i != vp2.size())continue;
	//	rep(j, n + 1) {
	//		if (dp[i][j] != INF)printf("%4d", dp[i][j]);
	//		else cout << " INF";
	//	}
	//	cout << endl;
	//}
	ll ans = INF;
	rep(i, n + 2) {
		ans = min(dp[vp2.size()][i] + n + 1 - now, ans);
	}
	cout << ans << endl;
	//cout << dp[vp2.size()][d] + n + 1 - now << endl;
}

//int n, m;
//vector<P> vp;
//int sum[100100];
//
//int main() {
//	cin >> n >> m;
//	vp.resize(m);
//	rep(i, m) {
//		int a, b;
//		cin >> a >> b;
//		sum[a]++;
//		sum[b]--;
//	}
//	rep(i, n + 2)sum[i + 1] += sum[i];
//	ll ans = 0;
//	rep(i, n + 1) {
//		if (sum[i] > 0)ans += 3;
//		else ans++;
//	}
//	cout << ans << endl;
//}
accuracy: 1
time_ms: 410
memory_kb: 7524
final_rank: 2

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <numeric>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <sstream>
#include <complex>
#include <fstream>
#include <bitset>
#include <time.h>
#include <tuple>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;

#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e12;
const ll MOD = 1e9 + 7;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,N) for(int i=0;i<(N);i++)
#define ALL(s) (s).begin(),(s).end()
#define EQ(a,b) (abs((a)-(b))<EPS)
#define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) )
#define fi first
#define se second
#define N_SIZE (1LL << 20)
#define NIL -1

ll sq(ll num) { return num*num; }
ll mod_pow(ll x, ll n) {
	if (n == 0)return 1;
	if (n == 1)return x%MOD;
	ll res = sq(mod_pow(x, n / 2));
	res %= MOD;
	if (n % 2 == 1) {
		res *= x;
		res %= MOD;
	}
	return res;
}
ll mod_add(ll a, ll b) { return (a + b) % MOD; }
ll mod_sub(ll a, ll b) { return (a - b + MOD) % MOD; }
ll mod_mul(ll a, ll b) { return a*b % MOD; }

//dp
int n, m;
vector<P> vp;
ll dp[510][1010];

int main() {
	cin >> n >> m;
	if (m == 0) {
		cout << n + 1 << endl;
		return 0;
	}
	rep(i, m) {
		ll c, d;
		cin >> c >> d;
		vp.push_back({ c,d });
	}
	sort(ALL(vp));
	vector<P> vp2;
	ll d = -1;
	rep(i, vp.size()) {
		if (d < vp[i].second) {
			d = vp[i].second;
			vp2.push_back(vp[i]);
		}
	}
	rep(i, 510)rep(j, 1010)dp[i][j] = INF;
	dp[0][0] = 0;
	int now = 0;
	rep(i, vp2.size()) {
		ll ci = vp2[i].first;
		ll di = vp2[i].second;
		FOR(j, di, n + 2) {//新しく経由する点
			FOR(k, now, n + 2) {//今までに経由した点
				if (k < j)dp[i + 1][j] = min(dp[i + 1][j], dp[i][k] + (j - now) + (j - ci));
				else dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + (ci - now));
			}
		}
		now = ci;
	}
	//FOR(i, 1, m + 1) {
	//	if (dp[i][5] == INF) {
	//		cout << i << endl;
	//		break;
	//	}
	//}
	//rep(i, m + 1) {
	//	rep(j, n + 1) {
	//		if (dp[i][j] != INF)printf("%4d", dp[i][j]);
	//		else cout << " INF";
	//	}
	//	cout << endl;
	//}
	d = vp.back().second;
	cout << dp[vp2.size()][d] + n + 1 - now << endl;
}

//int n, m;
//vector<P> vp;
//int sum[100100];
//
//int main() {
//	cin >> n >> m;
//	vp.resize(m);
//	rep(i, m) {
//		int a, b;
//		cin >> a >> b;
//		sum[a]++;
//		sum[b]--;
//	}
//	rep(i, n + 2)sum[i + 1] += sum[i];
//	ll ans = 0;
//	rep(i, n + 1) {
//		if (sum[i] > 0)ans += 3;
//		else ans++;
//	}
//	cout << ans << endl;
//}
accuracy: 0.045454545454545456
time_ms: 370
memory_kb: 7148
final_rank: 9

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <numeric>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <sstream>
#include <complex>
#include <fstream>
#include <bitset>
#include <time.h>
#include <tuple>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;

#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e12;
const ll MOD = 1e9 + 7;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,N) for(int i=0;i<(N);i++)
#define ALL(s) (s).begin(),(s).end()
#define EQ(a,b) (abs((a)-(b))<EPS)
#define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) )
#define fi first
#define se second
#define N_SIZE (1LL << 20)
#define NIL -1

ll sq(ll num) { return num*num; }
ll mod_pow(ll x, ll n) {
	if (n == 0)return 1;
	if (n == 1)return x%MOD;
	ll res = sq(mod_pow(x, n / 2));
	res %= MOD;
	if (n % 2 == 1) {
		res *= x;
		res %= MOD;
	}
	return res;
}
ll mod_add(ll a, ll b) { return (a + b) % MOD; }
ll mod_sub(ll a, ll b) { return (a - b + MOD) % MOD; }
ll mod_mul(ll a, ll b) { return a*b % MOD; }

//dp
int n, m;
vector<P> vp;
ll dp[510][1010];

int main() {
	cin >> n >> m;
	if (m == 0) {
		cout << n + 1 << endl;
		return 0;
	}
	rep(i, m) {
		ll c, d;
		cin >> c >> d;
		vp.push_back({ c,d });
	}
	sort(ALL(vp));
	rep(i, 510)rep(j, 1010)dp[i][j] = INF;
	dp[0][0] = 0;
	int now = 0;
	rep(i, m) {
		ll ci = vp[i].first;
		ll di = vp[i].second;
		FOR(j, di, n + 1) {//新しく経由する点
			FOR(k, now, n + 1) {//今までに経由した点
				if (k < j)dp[i + 1][j] = min(dp[i + 1][j], dp[i][k] + (j - now) + (j - ci));
				else dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + (ci - now));
			}
		}
		now = ci;
	}
	//rep(i, m + 1) {
	//	rep(j, n + 1) {
	//		if (dp[i][j] != INF)printf("%4d", dp[i][j]);
	//		else cout << " INF";
	//	}
	//	cout << endl;
	//}
	ll d = vp.back().second;
	cout << dp[m][d] + n + 1 - now << endl;
}

//int n, m;
//vector<P> vp;
//int sum[100100];
//
//int main() {
//	cin >> n >> m;
//	vp.resize(m);
//	rep(i, m) {
//		int a, b;
//		cin >> a >> b;
//		sum[a]++;
//		sum[b]--;
//	}
//	rep(i, n + 2)sum[i + 1] += sum[i];
//	ll ans = 0;
//	rep(i, n + 1) {
//		if (sum[i] > 0)ans += 3;
//		else ans++;
//	}
//	cout << ans << endl;
//}
accuracy: 0.045454545454545456
time_ms: 360
memory_kb: 7148
final_rank: 8

code_snippet: #include <bits/stdc++.h>
  
using namespace std;
  
#define rep(i,n) REP(i,0,n)
#define REP(i,s,e) for(int i=(s); i<(int)(e); i++)
#define repr(i, n) REPR(i, n, 0)
#define REPR(i, s, e) for(int i=(int)(s-1); i>=(int)(e); i--)
#define pb push_back
#define all(r) r.begin(),r.end()
#define rall(r) r.rbegin(),r.rend()
#define fi first
#define se second
  
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
 
const int INF = 1e9;
const ll MOD = 1e9 + 7;
double EPS = 1e-8;

ll dp[2][1010];

int main(){
    int n, m;
    cin >> n >> m;
    vi c(m+1), d(m+1);
    rep(i, m) cin >> c[i+1] >> d[i+1]; 
    if(m == 0) {
        cout << n+1 << endl;
        return 0;
    }
    vector<pii> p(m+1);
    rep(i, m+1) p[i] = make_pair(c[i], d[i]);
    sort(all(p));
    rep(i, m+1) {
        c[i] = p[i].fi;
        d[i] = p[i].se;
    }
    {
        rep(i, 1010) {
            dp[1][i] = 1e18;
        }
        REP(i, d[1], 1010) {
            dp[1][i] = i + i - c[1];
        }

    }
    int cur, nxt;
    REP(i, 1, m) {
        cur = i&1;
        nxt = (i+1)&1;
        rep(j, 1010) dp[nxt][j] = 1e18;
        // j番目からk番目まで進んでから、c[i]番目にいく
        rep(j, 1010) if(dp[cur][j] != 1e18) {
            REP(k, d[i+1], 1010) {
                if(j >= k) { // c[i] -> c[i+1]
                    int pos = max(j, c[i+1]);
                    dp[nxt][pos] = min(dp[nxt][pos], dp[cur][j] + c[i+1] - c[i]);
                }
                else { // c[i] -> k -> c[i+1]
                    int pos = max(k, c[i+1]);
                    dp[nxt][pos] = min(dp[nxt][pos], dp[cur][j] + abs(c[i] - k) + abs(k - c[i+1]));
                }
            }
        }
        // rep(j, 20) {
        //     cout << " " << (dp[nxt][j] == 1e18 ? -1 : dp[nxt][j]);
        // }
        // cout << endl;
    }

    ll ans = 1e18;
    rep(i, n+1) {
        ans = min(ans, dp[nxt][i] + n+1-c.back());
    }
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 830
memory_kb: 3152
final_rank: 5

code_snippet: #include<bits/stdc++.h>
using namespace std;
 
#define int long long
#define pb push_back 
#define pf push_front 
#define mp make_pair
#define fr first
#define sc second
#define Rep(i, n) for ( int i = 0 ; i < (n); i++ )
#define All(v) v.begin(), v.end()
 
typedef pair<int, int> Pii; typedef pair<int, Pii> Pip;
const int INF = 1107110711071107;
 
int N, m;
vector<Pii> d;
unordered_map<int, int> dp[1001][1001];
 
int dfs(int pre, int now, int n) {
  if ( n == m ) {
    return (now-pre + (N+1)-pre);
  }
  if ( dp[pre][now][n] > 0 ) return dp[pre][now][n];
 
  int ret = dfs(min(pre, d[n].sc), d[n].fr, n+1) + (d[n].fr-now);
  ret = min(ret, dfs(d[n].sc, d[n].fr, n+1) + (now-pre + d[n].fr-pre));
 
  return dp[pre][now][n] = ret;
}
 
signed main() {
  cin >> N >> m;
 
  Rep(i, m) {
    int c, b;
    cin >> c >> b;
    d.pb(Pii(b, c));    
  }
 
  sort(All(d));
 
  if ( m == 0 ) cout << N+1 << endl;
  else cout << dfs(d[0].sc, d[0].fr, 1) + d[0].fr << endl;
}
accuracy: 1
time_ms: 50
memory_kb: 65728
final_rank: 6

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

#define int long long
#define pb push_back 
#define pf push_front 
#define mp make_pair
#define fr first
#define sc second
#define Rep(i, n) for ( int i = 0 ; i < (n); i++ )
#define All(v) v.begin(), v.end()

typedef pair<int, int> Pii; typedef pair<int, Pii> Pip;
const int INF = 1107110711071107;

int N, m;
vector<Pii> d;
unordered_map<int, int> dp[1001][1001];

int dfs(int pre, int now, int n) {
  if ( n == m ) {
    return (now-pre + (N+1)-pre);
  }
  if ( dp[pre][now][n] > 0 ) return dp[pre][now][n];

  int ret = dfs(min(pre, d[n].sc), d[n].fr, n+1) + (d[n].fr-now);
  ret = min(ret, dfs(d[n].sc, d[n].fr, n+1) + (now-pre + d[n].fr-pre));

  return dp[pre][now][n] = ret;
}

signed main() {
  cin >> N >> m;

  Rep(i, m) {
    int c, b;
    cin >> c >> b;
    d.pb(Pii(b, c));    
  }

  sort(All(d));

  if ( m == 0 ) cout << N+1 << endl;
  else cout << dfs(d[0].sc, d[0].fr, 1) + d[0].fr << endl;
}
accuracy: 1
time_ms: 50
memory_kb: 65748
final_rank: 7

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

#define int long long
#define pb push_back 
#define pf push_front 
#define mp make_pair
#define fr first
#define sc second
#define Rep(i, n) for ( int i = 0 ; i < (n); i++ )
#define All(v) v.begin(), v.end()

typedef pair<int, int> Pii; typedef pair<int, Pii> Pip;
const int INF = 1107110711071107;

int N, m;
vector<Pii> d;
unordered_map<int, int> dp[1001][1001];

int dfs(int pre, int now, int n) {
  if ( n == m ) {
    return (now-pre + (N+1)-pre);
  }
  if ( dp[pre][now][n] > 0 ) return dp[pre][now][n];

  int ret = dfs(pre, d[n].fr, n+1) + (d[n].fr-now);
  ret = min(ret, dfs(d[n].sc, d[n].fr, n+1) + (now-pre + d[n].fr-pre));

  return dp[pre][now][n] = ret;
}

signed main() {
  cin >> N >> m;

  Rep(i, m) {
    int c, b;
    cin >> c >> b;
    d.pb(Pii(b, c));    
  }

  sort(All(d));

  if ( m == 0 ) cout << N+1 << endl;
  else cout << dfs(d[0].sc, d[0].fr, 1) + d[0].fr << endl;
}
accuracy: 0.045454545454545456
time_ms: 40
memory_kb: 63100
final_rank: 10

code_snippet: //#include <stdio.h>
//#include <iostream>
//#include <math.h>
//#include <numeric>
//#include <vector>
//#include <map>
//#include <functional>
//#include <stdio.h>
//#include <array>
//#include <algorithm>
//#include <string>
//#include <assert.h>
//#include <stdio.h>
//#include <queue>
//#include<iomanip>
//using namespace std;
//
//
//using namespace std;
////
////#define N (1<<17) 
////// update(l,r,v) := [l,r]の区間に対してvを一様に足す. k,a,bは飾り
////
////struct NODE{
////	int sum;//更新された値. この値を参照する時は評価が完全に完了しているようにする.
////	int lazy;	//遅延されている値を保存している
////	NODE(){
////		sum = lazy = 0;
////	}
////};
////
////NODE seg[2 * N];
////
////// inlineつけないと大変なことになるよ!(遅い)
////inline void lazy_evaluate_node(int k, int a, int b){
////	seg[k].sum +=seg[k].lazy;
////	if (k < N){ // 2*k(左の子番号) < 2*N (節点の数) のイメージで. 末端ノードじゃなきゃ伝搬するのと等価.
////		seg[2 * k].lazy += seg[k].lazy;	//次は君が伝搬してね☆って感じ.
////		seg[2 * k + 1].lazy += seg[k].lazy;
////	}
////	seg[k].lazy = 0;
////}
////
////inline void update_node(int k){ // kの子が既に評価されていることが前提. 末端以外のときしか呼び出さないような位置に書くのでif文要らない.
////	seg[k].sum = min(seg[2 * k].sum , seg[2 * k + 1].sum);
////}
////
////// update(l,r,v) := [l,r]を更新する. 区間は1-indexed.
////void update(int l, int r, int v, int k = 1, int a = 1, int b = N){
////	lazy_evaluate_node(k, a, b); 	// とりあえず辿ったノードは都合がいいので伝搬しとけ精神.
////
////	if (b < l || r < a) //[a,b]と[l,r]が交差している場合
////		return;
////	if (l <= a && b <= r){ // [l,r]が[a,b]を完全に含んでいる場合
////		seg[k].lazy += v;
////		lazy_evaluate_node(k, a, b); //一回遅延評価しとかないと都合悪いので.
////		return;
////	}
////
////	int m = (a + b) / 2;
////	update(l, r, v, 2 * k, a, m);
////	update(l, r, v, 2 * k + 1, m + 1, b);
////	update_node(k);
////}
////
////// get(l,r) := [l,r]に対するクエリの答えを得る. 区間は1-indexed.
////int get(int l, int r, int k = 1, int a = 1, int b = N){
////	lazy_evaluate_node(k, a, b); // とりあえず辿ったノードは都合がいいので伝搬しとけ精神.
////
////	if (b < l || r < a) //[a,b]と[l,r]が交差している場合
////		return 0;
////
////	if (l <= a && b <= r){ // [l,r]が[a,b]を完全に含んでいる場合
////		return seg[k].sum;
////	}
////
////	int m = (a + b) / 2;
////	int vl = get(l, r, 2 * k, a, m);
////	int vr = get(l, r, 2 * k + 1, m + 1, b);
////	update_node(k);
////	return min(vl , vr);
////}
//
//
//int main() {
//	//int n;
//	//cin >> n;
//	//vector<int> aa(n);
//	//vector<pair<int,int>>aaa;
//	//for (int i = 0; i < n; ++i){
//	//	int a, b;
//	//	cin >> a >> b;
//	//	aaa.push_back(make_pair(a, b)); 
//	//	aa[a]++;
//	//	aa[b]--;
//	//}
//	//vector<int> ans;
//	//ans.push_back(aa[0]);
//	//int amin=99999999;
//	//for(int i=0;i<n;++i){
//	//	ans.push_back(ans[i] + aa[i]);
//	//}
//
//	//RMQ r;
//	//r.init(65536);
//	//for (int i = 0; i < 65536;++i){
//	//	r.update(i, ans[i]);
//	//}
//
//	//cout << r.query(0, 7) << endl; //1
//	//cout << r.query(3, 6) << endl; //2
//	//cout << r.query(1, 5) << endl; //1
//	//cout << r.query(5, 7) << endl; //4
//	//return 0;
//
//	vector<long long int>times;
//	for (int i = 0; i < 7; ++i){
//		long long int c;
//		cin >> c;
//		times.push_back(c);
//	}
//	if (times[0] == 0)cout << "YES" << endl;
//	else{
//		times[0]--;
//	}
//
//	{
//		vector<long long int> atimes(times);
//		while (1){
//			auto zero_it = find(atimes.begin(), atimes.end(), 0);
//			if (zero_it != atimes.end()){//5 3 2 0 4 4 2 
//				const int num = zero_it - atimes.begin();
//				int from = num;
//				while (1){
//					from = (from + 1) % 7;
//					if (from == num)break;
//					int to = (from + 1) % 7;
//					if (atimes[from] != 0 && atimes[to] == 0){
//						break;
//					}
//					if (atimes[from] > atimes[to]){
//						break;
//					}
//					long long int amin = min(atimes[from], atimes[to]);
//					atimes[from] -= amin;
//					atimes[to] -= amin;
//					if (atimes[from] == 0 && atimes[to] == 0){
//						break;
//					}
//				}
//				if (all_of(atimes.begin(), atimes.end(), [](const int aaa){return aaa == 0; })){
//					cout << "YES" << endl;
//					return 0;
//				}
//				else{
//					break;
//				}
//			}
//			else{
//				long long int aamin = atimes[0];
//				for (int i = 0; i < 7; ++i){
//					aamin = min(aamin, atimes[i]);
//				}
//				for (int i = 0; i < 7; ++i){
//					atimes[i] -= aamin;
//				}
//			}
//		}
//	}
//	{
//		vector<long long int> btimes(times);
//		for (int i = 0; i < 7; ++i){//times[i]のまえがあいだになる
//			btimes = times;
//			int from = (i + 6) % 7;
//			while (1){
//				from = (from + 1) % 7;
//				if (from == (i + 6) % 7)break;
//				int to = (from + 1) % 7;
//				if (btimes[from] != 0 && btimes[to] == 0){
//					break;
//				}
//				if (btimes[from] > btimes[to]){
//					break;
//				}
//				long long int amin = min(btimes[from], btimes[to]);
//				btimes[from] -= amin;
//				btimes[to] -= amin;
//				if (btimes[from] == 0 && btimes[to] == 0){
//					break;
//				}
//			}
//			if (all_of(btimes.begin(), btimes.end(), [=](int a){return a == 0; })){
//				cout << "YES" << endl;
//				return 0;
//			}
//			else{
//				continue;
//			}
//		}
//	}
//	cout << "NO" << endl;
//	return 0;
//}
////3 4 4 4 4 4 4

#include<stdio.h>
#include <iostream>
#include <math.h>
#include <numeric>
#include <vector>
#include <map>
#include <functional>
#include <stdio.h>
#include <array>
#include <algorithm>
#include <string>
#include <assert.h>
#include <stdio.h>
#include <queue>
#include<iomanip>
#include<bitset>
#include<stack>
using namespace std;

//7:10
//
//#define REP(i,n) for(int i=0;i<(int)n;++i)
//#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
//#define ALL(c) (c).begin(), (c).end()
//
//typedef int Weight;
//struct Edge {
//	int src, dst;
//	Weight weight;
//	Edge(int src, int dst, Weight weight) :
//		src(src), dst(dst), weight(weight) { }
//};
//bool operator < (const Edge &e, const Edge &f) {
//	return e.weight != f.weight ? e.weight > f.weight : // !!INVERSE!!
//	e.src != f.src ? e.src < f.src : e.dst < f.dst;
//}
//typedef vector<Edge> Edges;
//typedef vector<Edges> Graph;
//
//typedef vector<Weight> Array;
//typedef vector<Array> Matrix;
//
//#define RESIDUE(s,t) (capacity[s][t]-flow[s][t])
//Weight maximumFlow(const Graph &g, int s, int t) {
//	int n = g.size();
//	Matrix flow(n, Array(n)), capacity(n, Array(n));
//	REP(u, n) for (auto e = g[u].begin(); e != g[u].end();++e)capacity[e->src][e->dst] += e->weight;
//
//	Weight total = 0;
//	while (1) {
//		queue<int> Q; Q.push(s);
//		vector<int> prev(n, -1); prev[s] = s;
//		while (!Q.empty() && prev[t] < 0) {
//			int u = Q.front(); Q.pop();
//			for (auto e = g[u].begin(); e != g[u].end(); ++e) if (prev[e->dst] < 0 && RESIDUE(u, e->dst) > 0) {
//				prev[e->dst] = u;
//				Q.push(e->dst);
//			}
//		}
//		if (prev[t] < 0) return total; // prev[x] == -1 <=> t-side
//		Weight inc = 999999999;
//		for (int j = t; prev[j] != j; j = prev[j])
//			inc = min(inc, RESIDUE(prev[j], j));
//		for (int j = t; prev[j] != j; j = prev[j])
//			flow[prev[j]][j] += inc, flow[j][prev[j]] -= inc;
//		total += inc;
//	}
//	return total;
//}
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()


const int mod = 1000000007;

struct Mod {
	long long int num;
	Mod() : num(0) { ; }
	Mod(long long int n) : num((n % mod + mod) % mod) { ; }
	operator long long int() { return num; }
};

Mod operator+(Mod a, Mod b) { return Mod((a.num + b.num) % mod); }
Mod operator-(Mod a, Mod b) { return Mod((mod + a.num - b.num) % mod); }
Mod operator*(Mod a, Mod b) { return Mod(((long long)a.num * b.num) % mod); }
Mod operator+=(Mod &a, Mod b) { return a = a + b; }
Mod operator-=(Mod &a, Mod b) { return a = a - b; }
Mod operator*=(Mod &a, Mod b) { return a = a * b; }
Mod operator^(Mod a, int n) {
	if (n == 0) return Mod(1);
	Mod res = (a * a) ^ (n / 2);
	if (n % 2) res = res * a;
	return res;
}
Mod inv(Mod a) { return a ^ (mod - 2); }
Mod operator/(Mod a, Mod b) { return a * inv(b); }

#define MAX_N 1024000

Mod fact[MAX_N], factinv[MAX_N];
void init() {
	fact[0] = Mod(1); factinv[0] = 1;
	REP(i, MAX_N - 1) {
		fact[i + 1] = fact[i] * Mod(i + 1);
		factinv[i + 1] = factinv[i] / Mod(i + 1);
	}
}
Mod comb(int a, int b) {
	return fact[a] * factinv[b] * factinv[a - b];
}

long long int memo[20];//nけた

long long int powint(long long int a, int b){
	if (b == 0)return 1;
	if (b == 1)return a;
	else{
		long long int ans = 1;
		long long int c = powint(a, b / 2);
		ans *= c*c;
		ans *= (b % 2) ? a : 1;
		return ans;
	}

}


int backnum[100000][20];

struct Node{
	Node(int aid):children(),ancs(){
		id=(aid);
		for (int i = 0; i < 20; ++i){
			ancs[i] = -1;
		}
	}
	int id;
	vector<int>children;
	array<int, 20>ancs;
};

int main()
{
	int N, M;
	cin >> N >> M;
	vector<int> Sa(N + 1);
	vector<int>Sum(N);
	for (int i = 0; i < M; ++i){
		int a, b;
		cin >> a >> b;
		if (a < b){
			Sa[a]++;
			Sa[b]--;
		}
		
	}
	int now = 0;
	for (int i = 0; i < N; ++i){
		now += Sa[i];
		Sum[i] += now;
	}
	int a = count_if(Sum.begin(), Sum.end(), [](const int l){return l != 0; });
	cout << N + 1 + a * 2<<endl;
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 19120
final_rank: 1