A13003 | Harmonious Graph
时间限制1s
内存限制256MB
通过 / 提交0/0
题目描述
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 < m < 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 < 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?
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 < m < 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 < 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?
输入格式
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).
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).
输出格式
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 < 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.
In the second example, the given graph is already harmonious.
C++ 编辑器
输入
输出
可保存默认模板;新题优先使用已保存模板。
当前快捷键仅展示,暂不支持修改。
- 撤销
Ctrl / ⌘ + Z - 重做
Ctrl / ⌘ + Y - 查找
Ctrl / ⌘ + F - 全选
Ctrl / ⌘ + A - 复制
Ctrl / ⌘ + C - 剪切
Ctrl / ⌘ + X - 粘贴
Ctrl / ⌘ + V - 自动排版
工具栏排版按钮 - 草稿保存
编辑时自动保存到本机
历史
提交记录
状态说明时间源码
AI
作答助手
你好,我是作答助手。可以问思路、复杂度、样例含义或代码报错原因;不会直接给出完整 AC 代码。
确定要清空代码吗?
提交通过
评测结果:Accepted