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<m<r≤n1≤l<m<r≤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<r), then we should able to reach nodes (l+1),(l+2),…,(r−1)(l+1),(l+2),…,(r−1) too.

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 <bits/stdc++.h>
#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;
}

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值