题意:求连通块中有多少个环。
题解:如果两数的祖先相同则总数加1,否则合并。
代码:
#include <cstdio>
int pre[2100],sum[2100],tot;
int find(int x){
int r = x;
while(pre[r] != r){
r = pre[r];
}
int i = x, j;
while(i != r){
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
void join(int x,int y){
int fx=find(x);
int fy=find(y);
if(fx!=fy)
pre[fy]=fx;
else tot++;
}
int main(){
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){
int a,b;
for(int i = 0; i < n; i++)
{
pre[i] = i;
}
tot=0;
for(int i=0;i<m;i++){
scanf("%d%d",&a,&b);
join(a,b);
}
printf("%d\n",tot);
}
return 0;
}
时间: 2024-11-01 12:30:58