#include<bits/stdc++.h>
#include "railroad.h"
#define ll long long
using namespace std;
const int inf=0x3f3f3f3f;
const int N=2e5+10;
int a1[N<<1],nn,fa[N<<1],pre[N<<1];
struct node{
int x,y,z;
}data[N<<1];
inline int find(int x){
while(x!=fa[x]) x=fa[x]=fa[fa[x]];return x;
}
inline void merge(int x,int y){
int fx=find(x),fy=find(y);
if (fx!=fy) fa[fx]=fy;
}
inline bool cmp(const node &a,const node &b){return a.z<b.z;}
long long plan_roller_coaster(std::vector<int> s, std::vector<int> t) {
int n = (int) s.size();s.push_back(inf);t.push_back(1);
for (int i=0;i<=n;++i) a1[++nn]=s[i],a1[++nn]=t[i];
sort(a1+1,a1+nn+1);nn=unique(a1+1,a1+nn+1)-a1-1;
for (int i=1;i<=nn;++i) fa[i]=i;
for (int i=0;i<=n;++i){
s[i]=lower_bound(a1+1,a1+nn+1,s[i])-a1;
t[i]=lower_bound(a1+1,a1+nn+1,t[i])-a1;
++pre[s[i]+1];--pre[t[i]+1];merge(s[i],t[i]);
}ll ans=0;
for (int i=1;i<=nn;++i) pre[i]+=pre[i-1];
for (int i=2;i<=nn;++i){
if (!pre[i]) continue;
if (pre[i]>0) ans+=1ll*pre[i]*(a1[i]-a1[i-1]);merge(i-1,i);
}int tot=0;
for (int i=2;i<=nn;++i) if (find(i-1)!=find(i)) data[++tot]=(node){i-1,i,a1[i]-a1[i-1]};
sort(data+1,data+tot+1,cmp);
for (int i=1;i<=tot;++i){
int x=data[i].x,y=data[i].y;
if (find(x)!=find(y)){
ans+=data[i].z;merge(x,y);
}
}
return ans;
}
int main() {
freopen("uoj236.in","r",stdin);
int n;
assert(1 == scanf("%d", &n));
int need_answer;
assert(1 == scanf("%d", &need_answer));
std::vector<int> s(n), t(n);
for (int i = 0; i < n; ++i)
assert(2 == scanf("%d%d", &s[i], &t[i]));
long long ans = plan_roller_coaster(s, t);
printf("%lld\n", ans);
return 0;
}