zoukankan      html  css  js  c++  java
  • HDU

    d.n个村庄m条路,求最少修多少条路可以连通所有的村庄

    s.并查集求出集合个数,减1即为答案

    c.

    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
    
    #define MAXN 1024
    
    int fa[MAXN];
    
    int set_find(int d){
        if(fa[d]<0)return d;
        return fa[d]=set_find(fa[d]);
    }
    
    void set_join(int x,int y){
        x=set_find(x);
        y=set_find(y);
        if(x!=y)fa[x]=y;
    }
    
    int main(){
        int N,M;
        int x,y;
        while(~scanf("%d",&N)){
            if(N==0)break;
            scanf("%d",&M);
    
            memset(fa,-1,sizeof(fa));
            for(int i=0;i<M;++i){
                scanf("%d%d",&x,&y);
                set_join(x,y);
            }
    
            int sum=0;
            for(int i=1;i<=N;++i)
                if(fa[i]==-1)
                    ++sum;
            printf("%d
    ",sum-1);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    Python-Matplotlib 12 多图figure
    Python-Matplotlib 11 子图-subplot
    Python Day16
    Python Day15
    Python Day13-14
    Python Day12
    Python Day11
    Python Day9-10
    Python Day8
    Python Day8
  • 原文地址:https://www.cnblogs.com/gongpixin/p/5017492.html
Copyright © 2011-2022 走看看