#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
long long arr[N] = {0};
vector<long long> grps[N];
long long ngrp = 1;
long long mergeGrp(int x, int y) {
  long long a = arr[x];
  long long b = arr[y];
  if (a == 0) {
    arr[x] = b;
    grps[b].push_back(x);
    return 1;
  }
  if (b == 0) {
    arr[y] = a;
    grps[a].push_back(y);
    return 1;
  }
  if (a == b) return 0;
  if (a > b) swap(a, b);
  for (auto i : grps[b]) {
    arr[i] = a;
    grps[a].push_back(i);
  }
  grps[b].clear();
  return 1;
}
void add(int a, int b) {
  if (arr[a] == 0 && arr[b] == 0) {
    grps[ngrp].push_back(a);
    grps[ngrp].push_back(b);
    arr[a] = arr[b] = ngrp++;
  } else if (arr[b] == 0) {
    grps[arr[a]].push_back(b);
    arr[b] = arr[a];
  } else if (arr[a] == 0) {
    grps[arr[b]].push_back(a);
    arr[a] = arr[b];
  } else {
    if (arr[a] != arr[b]) mergeGrp(a, b);
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long t = 1;
  while (t--) {
    long long a, b, c, d, n, m;
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
      cin >> a >> b;
      add(a, b);
    }
    long long ans = 0;
    for (int i = 0; i < N; i++) {
      if (grps[i].empty()) continue;
      sort(grps[i].begin(), grps[i].end());
      vector<long long> vec = grps[i];
      long long prevAns = ans;
      for (int j = 0; j < (vec.size() - 1); j++) {
        long long end = vec[j + 1];
        long long start = vec[j] + 1;
        while (start != end) {
          ans += mergeGrp(vec[j], start);
          start++;
        }
      }
      if (prevAns != ans) {
        i--;
      }
    }
    cout << ans << "\n";
  }
}
