并查集
解题思路
很明显的题目需要我们找到连通块个数减掉1就是答案了。那么问题就来到了求连通块个数,居然不带边权就不需要一个个dfs,直接跑并查集的裸板子就行了。
最后输出连通块个数。
Code
#pragma GCC target("avx,sse2,sse3,sse4,popcnt") #pragma GCC optimize("O2,O3,Ofast,inline,unroll-all-loops,-ffast-math") #include <bits/stdc++.h> using namespace std; #define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0) #define all(vv) vv.begin(), vv.end() typedef long long ll; typedef unsigned long long ull; typedef long double ld; const ll MOD = 1e9 + 7; inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar()) s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; } inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-'); int cnt = 0; while (tmp > 0) { F[cnt++] = tmp % 10 + '0'; tmp /= 10; } while (cnt > 0)putchar(F[--cnt]); } inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; } ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; } inline int lowbit(int x) { return x & (-x); } const int N = 1e5 + 7; int father[N]; int find(int root) { //路径压缩 int son = root; while (root != father[root]) root = father[root]; while (son != root) { int temp = father[son]; father[son] = root; son = temp; } return root; } void merge(int a, int b) { int fa = find(a); int fb = find(b); if (fa != fb) { father[fa] = fb; } } int main() { int n = read(), m = read(); for (int i = 1; i <= n; ++i) father[i] = i; for (int i = 1; i <= m; ++i) { int u = read(), v = read(); merge(u, v); } int ans = 0; for (int i = 1; i <= n; ++i) if (father[i] == i) ++ans; write(ans - 1); return 0; }