3 solutions

  • 0
    @ 2023-4-5 16:09:36
    #include<bits/stdc++.h>
    using namespace std;
    
    const int N = 1e3+7;
    int nums[N];
    // 使用并查集思想,使用并查集计算出孤立的点n(孤立的点即自己是自己的祖先),答案为n-1
    
    void init(){
        for (int i = 1; i < N; i++) {
            nums[i] = i;
        }
    }
    
    int find(int x) {
        while (x != nums[x]) {
            x = nums[x];
        }
        return x;
    }
    
    void merge(int a, int b){
        int af = find(a);
        int bf = find(b);
        if (af != bf) nums[bf] = af;
    }
    
    
    int main (){
        int n, m;
        while (~ scanf("%d %d", &n, &m) & n) {
            init();
            // 使孤立的点连接起来
            for (int i = 1; i <= m; i++) {
                int a, b;
                scanf("%d %d", &a, &b);
                merge(a, b);
            }
    
            // 计算连接后,一共有n个部分,答案为n-1
            int sum = 0;
            for (int i = 1; i <= n; i++) {
                if (nums[i] == i) sum++;
            }
            printf("%d\n", sum - 1);
        }
    
    
        return 0;
    }
    

    Information

    ID
    1258
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    5
    Tags
    # Submissions
    110
    Accepted
    44
    Uploaded By