PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#DSU0000037. Đồ thị hài hòa (Harmonious Graph)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đồ 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 nn vertices numbered from 11 to nn and mm 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 l<m<rl<m<r, whenever ll and rr are connected, ll and mm 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 n,mn,m. Each of the next mm lines is an edge u,vu,v of a simple graph (u≠vu\ne v, no duplicate edges).

Output

Print the minimum number of additional edges.

Subtasks

  • Subtask 1 (20 points): 3≤n≤253\le n\le25, 1≤m≤3001\le m\le300; 1≤u,v≤n1\le u,v\le n, u≠vu\ne v; the graph is simple and has no duplicate edges.
  • Subtask 2 (30 points): 3≤n≤20003\le n\le2000, 1≤m≤2⋅1051\le m\le2\cdot10^5; 1≤u,v≤n1\le u,v\le n, u≠vu\ne v; the graph is simple and has no duplicate edges.
  • Subtask 3 (50 points): 3≤n≤2⋅1053\le n\le2\cdot10^5, 1≤m≤2⋅1051\le m\le2\cdot10^5; 1≤u,v≤n1\le u,v\le n, u≠vu\ne v; 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 11 also contains 2,5,72,5,7, whereas the component containing vertex 33 also contains 4,6,84,6,8. Their index ranges overlap, so adding one edge between these components makes every component occupy a consecutive interval of indices. The answer is 1.