天天看點

Codeforces Round #600 (Div. 2) D題

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.

并查集+思維;

對每個集合的最大最小值之間的值進行枚舉,如果父親不相同,則連接配接起來,并且邊數加一;

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=200100;
const int M=200100;
const LL mod=998244353;
int n,m;
int fa[N];
int find(int p){
	if(p==fa[p]) return p;
	return fa[p]=find(fa[p]);
}
int vis[N];
struct Node{
	int mmin,mmax;
}bin[N];
bool cmp(Node p,Node q){
	return p.mmin<q.mmin;
}
bool d[N];
int main(){
//	ios::sync_with_stdio(false);
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		bin[i].mmax=0;
		bin[i].mmin=2e9;
		fa[i]=i;
	}
	int u,v;
	int ans=0;//并查集的數量 
	for(int i=1;i<=m;i++){
		scanf("%d%d",&u,&v);
		if(!vis[u]&&!vis[v]){
			ans++;
			vis[u]=vis[v]=ans;
		}
		else if(vis[u]||vis[v]){
			if(vis[u]) vis[v]=vis[u];
			else vis[u]=vis[v];
		}
		if(u>v){
			fa[find(v)]=find(fa[u]);
			bin[vis[u]].mmax=bin[vis[u]].mmax>u?bin[vis[u]].mmax:u;
			bin[vis[u]].mmin=bin[vis[u]].mmin<v?bin[vis[u]].mmin:v;
		}
		else{
			fa[find(u)]=find(fa[v]);
			bin[vis[u]].mmax=bin[vis[u]].mmax>v?bin[vis[u]].mmax:v;
			bin[vis[u]].mmin=bin[vis[u]].mmin<u?bin[vis[u]].mmin:u;
		}
	}
	sort(bin+1,bin+1+ans,cmp);
	int sum=0;
	int last=0;
	for(int i=1;i<=ans;i++){
		int f=find(bin[i].mmin);//整個集合的父親 
		last=max(last,bin[i].mmin);
		for(int j=last;j<bin[i].mmax;j++){
			if(d[j]) continue;//剪枝 
			d[j]=true;
			if(find(fa[j])!=f){
				if(fa[j]==j){//如果是連接配接的自己 
					fa[j]=f;
					sum++;
				}
				else{
					if(fa[j]>f){//如果在其他的集合裡面 
						fa[find(f)]=find(fa[j]);
						f=find(fa[j]);
					}
					else{
						fa[find(fa[j])]=find(f);
					}
					sum++;
				}
			}
		}
		last=bin[i].mmax;
	}
	printf("%d\n",sum);
	return 0;
}