D. Harmonious Graph (Codeforces Round # 600 (Div. 2)) (disjoint-set thinking +)
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:
answer
If there is path, then The communication block must be able to reach all points. And if and maximum point of attachment is So, communicates and blocks only connected on the line. Therefore, we maintain maximum value for all blocks in the current through the communication of, just need to find less than 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;
}