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\n",sum-1); } return 0; }
时间: 2024-10-01 05:13:15