CodeForces 1253D Harmonious Graph (并查集)

题意:给出n个点m条边,要使得每一个连通图包含的点都是编号连续的点,求还需要添加多少条边。

题解:并查集
既然是连续编号的点,我们得选择一个具有特征的点作为根,这里选择集合中最大的点。
接下来遍历所有点,对于点 i i i,其根为 t e m p temp temp t e m p > = i temp>=i temp>=i,那么 [ i , t e m p ] [i, temp] [i,temp]所包含的点必然要跟点 i i i t e m p temp temp连接,这样更新 t e m p = m a x ( ) temp=max() temp=max()即可。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int Max = 2e5 + 5;
int Parent[Max], Rank[Max], repair[Max], cnt;;
int Find(int x) {
	return Parent[x] == x ? x : Parent[x] = Find(Parent[x]);
}
void Union(int x, int y) {
	int u, v, root;
	u = Find(x);
	v = Find(y);
	if (u == v) {
		return;
	}
	if (u < v) {
		root = Parent[u] = v;
	}
	else
		root = Parent[v] = u;
	//return root;
}
int n, m, u, v;
int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++) Parent[i] = i;
	for (int i = 1; i <= m; i++) {
		scanf("%d%d", &u, &v);
		Union(u, v);
	}
	int num = 0;
	for (int i = 1; i <= n; i++) {
		int temp = Find(i);
		for (int j = i + 1; j < temp; j++) {
			int p = Find(j);
			if (p != temp) {
				Union(p, temp);
				temp = max(p, temp);
				num++;
			}
		}
		i = temp;
	}
	printf("%d\n", num);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值