#DSU0000037. Đồ thị hài hòa (Harmonious Graph)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Đồ thị hài hòa (Harmonious Graph)
Harmonious Graph
Source: Codeforces
Version: Phuoc Hung OJ Extended
Problem Statement
You are given an undirected graph with vertices numbered from to and edges. Two vertices are connected if a path joins them; a vertex is connected to itself.
The graph is harmonious if, for every three indices , whenever and are connected, and must also be connected. Equivalently, the vertices of each connected component must form a consecutive interval of indices.
You may add undirected edges between vertices that are not already adjacent, but you cannot remove existing edges. Find the minimum number of edges to add to make the graph harmonious.
Input
The first line contains . Each of the next lines is an edge of a simple graph (, no duplicate edges).
Output
Print the minimum number of additional edges.
Subtasks
- Subtask 1 (20 points): , ; , ; the graph is simple and has no duplicate edges.
- Subtask 2 (30 points): , ; , ; the graph is simple and has no duplicate edges.
- Subtask 3 (50 points): , ; , ; the graph is simple and has no duplicate edges.
Examples
Input
14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12
Output
1
Explanation
Initially, the component containing vertex also contains , whereas the component containing vertex also contains . Their index ranges overlap, so adding one edge between these components makes every component occupy a consecutive interval of indices. The answer is 1.