总结10

· · 个人记录

村村通

#include<bits/stdc++.h>

using namespace std;

int n, m, a[1005], x, y;

int find(int x){
    if(a[x] == x){
        return a[x];
    }
    return a[x] = find(a[x]);
}

void h(int x, int y){
    int a1 = find(x), a2 = find(y);
    if(a1 != a2){
        a[a2] = a1;
    }
}

int main(){
    while(1){
        int ans = 0;
        cin >> n;
        if(n == 0){
            return 0;
        } 
        cin >> m;
        for(int i = 1; i <= n; i++){
            a[i] = i;
        }
        for(int i = 1; i <= m; i++){
            cin >> x >> y;
            h(x, y);
        }
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= n; j++){
                if(find(i) != find(j)){////判断两个数是否在同一集合。
                    ans++;
                    h(i, j);
                }
            }
        }
        cout << ans << '\n';
    }
    return 0;
} 

思路:首先,用并查集将道路连起来。然后,如果两个村庄不在一个集合内,那么就将这两个集合连起来,并且道路数量加1。

T703065 无向图判环

做这道题之前我们首先了解一下环。

环的定义:环是指从一个顶点出发,沿着边移动,最终回到起始顶点的路径,且路径中不重复经过任何顶点。

代码

#include<bits/stdc++.h>

using namespace std;

int n, m, a[10005], t, x, y;
int find(int x){
    if(a[x] == x){
        return a[x];
    }
    return find(a[x]);
}

void h(int x, int y){
    int a1 = find(x), a2 = find(y);
    if(a1 != a2){
        a[a2] = a1;
    }
}

int main(){
    cin >> t;
    while(t--){
        cin >> n >> m;
        bool f = 1;
        for(int i = 1; i <= n; i++){
            a[i] = i;
        }
        for(int i = 1; i <= m; i++){
            cin >> x >> y;
            if(find(x) == find(y)){//如果两个数有其他方式连接,就是一个环
                f = 0;
            }
            h(x, y);
        }
        if(f){
            cout << "No\n";
        }
        else{
            cout << "Yes\n";
        }
    }
    return 0;
} 

思路: 首先,我们要把在find函数中的优化去掉。 然后,遍历所有数,如果可以遍历到自己,就形成了一个环。