#include <bits/stdc++.h>
using namespace std;
struct disjointSetNode {
  int data;
  int rank;
  struct disjointSetNode* parent;
  int frequency;
};
map<int, disjointSetNode*> disjointSet;
void makeSet(int element) {
  struct disjointSetNode* root = new disjointSetNode;
  root->data = element;
  root->rank = 0;
  root->parent = root;
  root->frequency = 1;
  disjointSet[element] = root;
}
struct disjointSetNode* findSet(struct disjointSetNode* root) {
  struct disjointSetNode* parent = root->parent;
  if (parent == root) {
    return parent;
  }
  root->parent = findSet(root->parent);
  return root->parent;
}
int Union(int element1, int element2) {
  struct disjointSetNode* parent1 = findSet(disjointSet[element1]);
  struct disjointSetNode* parent2 = findSet(disjointSet[element2]);
  if (parent1->data == parent2->data) {
    return 0;
  }
  if (parent1->rank >= parent2->rank) {
    parent1->rank =
        (parent1->rank = parent2->rank) ? parent1->rank + 1 : parent1->rank;
    parent2->parent = parent1;
    parent1->frequency += parent2->frequency;
  } else {
    parent1->parent = parent2;
    parent2->frequency += parent1->frequency;
  }
  return 1;
}
int elementsInSet(int element) {
  struct disjointSetNode* root = disjointSet[element]->parent;
  while (root->parent != root) {
    root = root->parent;
  }
  return root->frequency;
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= n; ++i) {
    makeSet(i);
  }
  for (int i = 0; i < m; ++i) {
    int u, v;
    cin >> u >> v;
    Union(u, v);
  }
  int ans = 0;
  for (int l = 1; l <= n;) {
    int cur = elementsInSet(l);
    for (int j = l; j <= l + cur - 1; ++j) {
      ans += Union(l, j);
      cur = elementsInSet(l);
    }
    l += cur;
  }
  cout << ans;
  return 0;
}
