#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 50;
const int INF = 0x3f3f3f3f;
int far[maxn];
int find(int x) {
  if (far[x] == x)
    return x;
  else
    return far[x] = find(far[x]);
}
void init(int n) {
  for (int i = 0; i <= n; i++) far[i] = i;
}
int main() {
  std::ios::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  init(n);
  while (m--) {
    int a, b;
    cin >> a >> b;
    a = find(a);
    b = find(b);
    if (a > b) swap(a, b);
    far[a] = b;
  }
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    int x = find(i);
    while (i < x) {
      int y = find(i);
      if (x != y) {
        ans++;
        if (x < y) swap(x, y);
        far[y] = x;
      }
      i++;
    }
  }
  cout << ans << endl;
  return 0;
}
