Harmonious Graph (并查集 —父亲为最大值)

You’re given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n.

The graph is considered harmonious if and only if the following property holds:

For every triple of integers (l,m,r) such that 1≤l<m<r≤n, if there exists a path going from node l to node r, then there exists a path going from node l to node m.
In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l<r), then we should able to reach nodes (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 n and m (3≤n≤200 000 and 1≤m≤200 000).

The i-th of the next m lines contains two integers ui and vi (1≤ui,vi≤n, ui≠vi), that mean that there’s an edge between nodes u and v.

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
Note
In the first example, the given graph is not harmonious (for instance, 1<6<7, node 1 can reach node 7 through the path 1→2→7, but node 1 can’t reach node 6). However adding the edge (2,4) is sufficient to make it harmonious.

In the second example, the given graph is already harmonious.

#pragma warning(disable:4996)
#include"iostream"
#include"functional"
#include"algorithm"
#include"cstring"
#include"stack"
#include"cmath"
#include"queue"
#include"vector"
#include"map"
typedef long long int ll;
using namespace std;
ll fa[9999999];
ll find(ll a){
	if(a==fa[a]) return a;
	else{
		return fa[a]=find(fa[a]);
	}
}
int main(){
	ll a,b;
	cin>>a>>b;
	for(int i=1;i<=a;i++) fa[i]=i;
    for(int i=0;i<b;i++){
        ll c,d;
        cin>>c>>d;
        ll fc=find(c),fd=find(d);
        if(fc<fd) fa[fc]=fd;
        else if(fc>fd){
        	fa[fd]=fc;
		}
	}
	ll ans=0;
	for(int i=1;i<=a;i++){
		ll k=find(i);
		while(k>i){
			ll j=find(i);
			if(j!=k){
				ans++;
				fa[min(j,k)]=max(j,k);
				k=max(k,j);
			}
			i++;
		}
	}
    cout<<ans;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值