CF1253D.Harmonious Graph

普及+/提高

通过率:0%

时间限制:1.00s

内存限制:256MB

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

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 1≤l<m<r≤n1 \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),…,(r−1)(l+1), (l+2), \ldots, (r-1) too.

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

给你一个包含 nn 个节点和 mm 条边的无向图。节点编号为 11 到 nn。

当且仅当满足以下性质时,该图被称为和谐图:

  • 对于任意三元组整数 (l,m,r)(l, m, r),若 1≤l<m<r≤n1 \le l \lt m \lt r \le n,且存在一条从节点 ll 到节点 rr 的路径,则必定存在一条从节点 ll 到节点 mm 的路径。

换言之,在一个和谐图中,若从节点 ll 出发(l<rl \lt r)能通过边到达节点 rr,则也必须能到达所有中间节点 l+1,l+2,…,r−1l+1, l+2, \ldots, r-1。

问:使该图变为和谐图所需添加的最少边数是多少?

输入格式

The first line contains two integers nn and mm (3≤n≤200 0003 \le n \le 200\ 000 and 1≤m≤200 0001 \le m \le 200\ 000).

The ii-th of the next mm lines contains two integers uiu_i and viv_i (1≤ui,vi≤n1 \le u_i, v_i \le n, ui≠viu_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).

第一行包含两个整数 nn 和 mm(3≤n≤200 0003 \le n \le 200\ 000,1≤m≤200 0001 \le m \le 200\ 000)。

接下来的 mm 行中,第 ii 行包含两个整数 uiu_i 和 viv_i(1≤ui,vi≤n1 \le u_i, v_i \le n,ui≠viu_i \neq v_i),表示节点 uu 与节点 vv 之间存在一条边。

保证所给图是简单图(即不存在自环,且任意两个节点之间至多只有一条边)。

输出格式

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

    1
  • 输入#2

    200000 3
    7 9
    9 8
    4 5

    输出#2

    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 1→2→71 \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.

在第一个例子中,给定的图不是和谐的(例如,1<6<71 \lt 6 \lt 7,节点 11 可通过路径 1→2→71 \rightarrow 2 \rightarrow 7 到达节点 77,但节点 11 无法到达节点 66)。然而,添加边 (2,4)(2, 4) 就足以使其变为和谐图。

在第二个例子中,给定的图本身已是和谐的。

输入解题思路,AI测评打分。不知道怎么写?

首页