#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int n, m;
int f[maxn];
void init() {
  for (int i = 1; i <= n; i++) f[i] = i;
}
int get(int x) {
  if (x == f[x]) return x;
  return f[x] = get(f[x]);
}
int main() {
  cin >> n >> m;
  init();
  for (int i = 1; i <= m; i++) {
    int a, b;
    cin >> a >> b;
    a = get(a);
    b = get(b);
    if (a > b) {
      swap(a, b);
    }
    f[a] = b;
  }
  int ans = 0;
  int cnt = 1;
  while (cnt <= n) {
    int ff = get(cnt);
    while (++cnt <= ff) {
      int fa = get(cnt);
      if (ff != fa) {
        if (fa > ff) {
          swap(fa, ff);
        }
        f[fa] = ff;
        ans++;
      }
    }
  }
  cout << ans;
  return 0;
}
