明说是图,实际是并查集
题意是根据结点和边得个数可以得到图的个数,答案就是 (图的个数 - 1 )
根据样例
#include<bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; int f[maxn]; int find ( int x) { if ( x == f[x]) return x; return f[x] = find(f[x]); } int main() { int n, m; cin >> n >> m; for ( int i = 0; i < n; i++) f[i] = i; for ( int i = 0; i < m; i++) { int a, b; cin >> a >> b; int x = find(a); int y = find(b); if ( x != y) { f[y] = x; } } int ans = 0; for ( int i = 0; i < n; i++) { if ( f[i] == i) ans++; } cout << ans - 1; system("pause"); }
/*
把所有操作分开的代码
*/
#include<bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; int f[maxn]; int find ( int x) { // 查找 + 路径压缩 if ( x == f[x]) return x; return f[x] = find(f[x]); } void sset( int n) { // for ( int i = 0; i < n; i++) f[i] = i; } void merge ( int m) { // 合并 for ( int i = 0; i < m; i++) { int a, b; cin >> a >> b; int x = find(a); int y = find(b); if ( x != y) { f[y] = x; } } } int main() { int n, m; cin >> n >> m; sset(n); merge(m); int ans = 0; for ( int i = 0; i < n; i++) { if ( f[i] == i) ans++; } cout << ans - 1; }