#include <bits/stdc++.h>
using namespace std;
const long long llinf = 9000000000000000000;
const int inf = 2000000000;
int n, m;
pair<int, int> edge[200010];
struct UNION_FIND {
  int par[200010], qu;
  void init() {
    for (int i = 1; i <= n; i++) par[i] = i;
  }
  int findpar(int num) {
    if (num == par[num]) return num;
    return par[num] = findpar(par[num]);
  }
  void mergepar(int a, int b) {
    a = findpar(a);
    b = findpar(b);
    if (a == b) return;
    qu--;
    par[a] = b;
  }
} uf;
int ans;
int f(int fr, int re, int a, int b) {
  uf.qu = re - fr + 1;
  for (int i = a; i <= b; i++) {
    uf.mergepar(edge[i].first, edge[i].second);
  }
  return uf.qu;
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int a, b;
    scanf("%d %d", &a, &b);
    if (a > b) swap(a, b);
    edge[i] = make_pair(a, b);
  }
  sort(edge + 1, edge + m + 1);
  int fr = edge[1].first, re = edge[1].second, t = 1;
  uf.init();
  for (int i = 2; i <= m; i++) {
    if (re < edge[i].first) {
      ans += f(fr, re, t, i - 1) - 1;
      t = i;
      fr = edge[i].first;
      re = edge[i].second;
    } else {
      re = max(edge[i].second, re);
    }
  }
  ans += f(fr, re, t, m) - 1;
  printf("%d", ans);
}
