D. Harmonious Graph(Codeforces Round #600 (Div. 2))(并查集+思维)
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
样例1:
题解
如果有 的路径的话,那么 这个连通块就必须能够到达 所有的点。而如果和 相连的最大的点是 那么, 连通块只需要和 相连就行了。所以我们维护 为当前走过的所有连通块的最大值,只需要找到小于 的点就说明这里本该有一条边,因为题上已经给出了一些边,所以减去这些之中有效的那部分就是答案了。
代码
#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;
}