Codeforces Round 600 (Div. 2)
D
Harmonious Graph
Codeforces
1700
原题
← CE →
翻译中…

You're given an undirected graph with $n$ nodes and $m$ edges. Nodes are numbered from $1$ to $n$.

翻译中…

The graph is considered harmonious if and only if the following property holds:

翻译中…
  • For every triple of integers $(l, m, r)$ such that $1 \le l \lt m \lt r \le n$, if there exists a path going from node $l$ to node $r$, then there exists a path going from node $l$ to node $m$.
翻译中…

In other words, in a harmonious graph, if from a node $l$ we can reach a node $r$ through edges ($l \lt r$), then we should able to reach nodes $(l+1), (l+2), \ldots, (r-1)$ too.

翻译中…

What is the minimum number of edges we need to add to make the graph harmonious?

翻译中…

Input

翻译中…

The first line contains two integers $n$ and $m$ ($3 \le n \le 200\ 000$ and $1 \le m \le 200\ 000$).

翻译中…

The $i$-th of the next $m$ lines contains two integers $u_i$ and $v_i$ ($1 \le u_i, v_i \le n$, $u_i \neq v_i$), that mean that there's an edge between nodes $u$ and $v$.

翻译中…

It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).

翻译中…

Output

翻译中…

Print the minimum number of edges we have to add to the graph to make it harmonious.

翻译中…

Note

翻译中…

In the first example, the given graph is not harmonious (for instance, $1 \lt 6 \lt 7$, node $1$ can reach node $7$ through the path $1 \rightarrow 2 \rightarrow 7$, but node $1$ can't reach node $6$). However adding the edge $(2, 4)$ is sufficient to make it harmonious.

翻译中…

In the second example, the given graph is already harmonious.

翻译中…

样例

Input #1
14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12
Output #1
1
InputCopy OutputCopy
Input #2
200000 3
7 9
9 8
4 5
Output #2
0
InputCopy OutputCopy
题目信息
题号
1253D
时间限制
1 s
内存限制
256 MB
标签
构造
DFS 及类似
并查集
图论
贪心
排序

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。