← Home
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 1024*1024), 10*1024*1024)
	scanner.Split(bufio.ScanWords)

	nextInt := func() int {
		scanner.Scan()
		res := 0
		for _, b := range scanner.Bytes() {
			if b >= '0' && b <= '9' {
				res = res*10 + int(b-'0')
			}
		}
		return res
	}

	n := nextInt()
	if n == 0 {
		return
	}
	m := nextInt()

	parent := make([]int, n+1)
	maxNode := make([]int, n+1)
	for i := 1; i <= n; i++ {
		parent[i] = i
		maxNode[i] = i
	}

	var find func(i int) int
	find = func(i int) int {
		root := i
		for root != parent[root] {
			root = parent[root]
		}
		curr := i
		for curr != root {
			nxt := parent[curr]
			parent[curr] = root
			curr = nxt
		}
		return root
	}

	union := func(i, j int) {
		rootI := find(i)
		rootJ := find(j)
		if rootI != rootJ {
			parent[rootI] = rootJ
			if maxNode[rootI] > maxNode[rootJ] {
				maxNode[rootJ] = maxNode[rootI]
			}
		}
	}

	for i := 0; i < m; i++ {
		u := nextInt()
		v := nextInt()
		union(u, v)
	}

	ans := 0
	currentMax := 0

	for i := 1; i <= n; i++ {
		root := find(i)
		if currentMax < i {
			currentMax = maxNode[root]
		} else {
			rootPrev := find(i - 1)
			if root != rootPrev {
				ans++
				union(root, rootPrev)
				root = find(i)
			}
			if maxNode[root] > currentMax {
				currentMax = maxNode[root]
			}
		}
	}

	fmt.Println(ans)
}