栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Harmonious Graph

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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≤lIn 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;
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769559.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号