D. Harmonious Graph (Codeforces Round # 600 (Div. 2)) (disjoint-set thinking +)

D. Harmonious Graph (Codeforces Round # 600 (Div. 2)) (disjoint-set thinking +)

Here Insert Picture Description
Here Insert Picture Description

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

Example 1:
Here Insert Picture Description

answer

If there is 1 n 1-n path, then 1 n 1-n The communication block must be able to reach 2 , 3 , 4...11 2,3,4...11 all points. And if and 1 1 maximum point of attachment is 7 7 So, 1 7 1-7 communicates and blocks only 2 , 3 , 4 , 5 , 6 2,3,4,5,6 connected on the line. Therefore, we maintain l a r lar maximum value for all blocks in the current through the communication of, just need to find less than l a r lar of this point to explain that there is an edge here, because the title already gives some edge, so that part is minus effective among these answers.

Code

#include <bits/stdc++.h>
using namespace std;
const int N = 200020;

int res;
int lab[N];
int n, m;

int find(int x) {
	return lab[x] < 0 ? x : lab[x] = find(lab[x]);
}

void join(int x, int y) {
	x = find(x); y = find(y);
	if (x == y) return;
	if (x < y) swap(x, y);
	res++;
	lab[y] = x;
}

int main() {
	//freopen("in.txt", "r", stdin);
	ios_base::sync_with_stdio(false); cin.tie(NULL);

	memset(lab, -1, sizeof lab);

	cin >> n >> m;
	res = 0;
	for (int i = 1; i <= m; ++i) {
		int u, v; cin >> u >> v;
		join(u, v);
	}

	int comp = 0, lar = find(1);
	for (int i = 2; i <= n; ++i) {
		if (i <= lar) ++comp;
		lar = max(lar, find(i));
	}

	cout << comp - res << endl;

	return 0;
}
Published 163 original articles · won praise 54 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_42856843/article/details/103115497