CF1253D.Harmonious Graph

传统题 时间 1000 ms 内存 256 MiB 8 尝试 43 已通过 7 标签

Harmonious Graph

CF1253D · Harmonious Graph

  • 难度:1700
  • 标签:constructive algorithms、dfs and similar、dsu、graphs、greedy、sortings
  • 链接:https://codeforces.com/problemset/problem/1253/D
  • 时间限制:1 second 内存限制:256 megabytes
  • 出现位置:Day12-Kruskal-离线排序-路径贡献

英文原题面

Statement

You're given an undirected graph with nn nodes and mm edges. Nodes are numbered from 11 to nn. The graph is considered harmonious if and only if the following property holds:

  • For every triple of integers (l,m,r)(l, m, r) such that 1l<m<rn1 \le l \lt m \lt r \le n, if there exists a path going from node ll to node rr, then there exists a path going from node ll to node mm.

In other words, in a harmonious graph, if from a node ll we can reach a node rr through edges (l<rl \lt r), then we should able to reach nodes (l+1),(l+2),,(r1)(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 nn and mm (3n200 0003 \le n \le 200\ 000 and 1m200 0001 \le m \le 200\ 000). The ii-th of the next mm lines contains two integers uiu_i and viv_i (1ui,vin1 \le u_i, v_i \le n, uiviu_i \neq v_i), that mean that there's an edge between nodes uu and vv. 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.

样例

样例 1

输入:

14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12

输出:

1

样例 2

输入:

200000 3
7 9
9 8
4 5

输出:

0

样例解释(英文原文)

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

在线编程 IDE

建议全屏模式获得最佳体验