天天看點

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