Harmonious Graph

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

In other words, in a harmonious graph, if from a node ll we can reach a node rr through edges (l

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 (3≤n≤200 0003≤n≤200 000 and 1≤m≤200 0001≤m≤200 000).

The ii-th of the next mm lines contains two integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi), 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.

Examples

input

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

output

1

input

200000 3
7 9
9 8
4 5

output

0

假如1->2>7就要让1能到1->3,1->4,1->5,1->6,假如1->3,1->7被连接,也就是3->7也连接了,所以如果用并查集维护的时候,父节点相同的就是连接的点。我们要使得,每个集合中最大的点为根(设为k),其余节点分别为:1-k-1。也就是说每个并查集必须含有(1-k)的所有整数值。

#include 
#define rep(i, a, b) for(int i = a; i <= b; ++i)
#define per(i, a, b) for(int i = a; i >= b; --i)
using namespace std;

const int N = 200010;

int p[N];

int find(int x){
	if(p[x] == x) return x;
	else return p[x] = find(p[x]);
}

int main()
{
	int n,m; cin >> n >> m;
	rep(i,1,n) p[i] = i;
	rep(i,1,m){
		int a,b; cin >> a >> b;
		int px = find(a),pb = find(b);
//		让大的数为父亲
		if(px < pb){
			p[px] = pb;
		}else {
			p[pb] = px;
		}
	}
	
	int t = 1,maxn = 1,ans = 0;
	while(t <= n){
		maxn = find(t);
		rep(i,t+1,maxn){//要让t,到maxn间的值为一个集合
			int x = find(i);
			if(x != maxn){
				ans++;
				if(x > maxn){
					p[maxn] = x;
					maxn = x;// 集合应该是更大的范围。
				}else{
					p[x] = maxn;// 合并两集合
				}
			}
		}
		t = maxn + 1;
	}
	cout << ans << endl;
    return 0;
}

 

你可能感兴趣的:(codeforces补题,c++,图论,算法,acm竞赛,蓝桥杯)