This question is very similar to HDU 1213 how many tables and query sets.
Idea: Suppose we still need to build n-1 routes, and each merge will be reduced by 1.
Reference code:
#include<stdio.h>int fa[1000];int find(int u){ return fa[u]==u?u:fa[u]=find(fa[u]);}int main(){ int i,n,m,u,v,x,y; scanf("%d%d",&n,&m); while (n) { for (i=1;i<=n;i++) fa[i]=i; for (i=1;i<=m;i++) { scanf("%d%d",&u,&v); x=find(u);y=find(v); if (x!=y) { fa[x]=y; n--; } } n--; printf("%d\n",n); scanf("%d%d",&n,&m); } return 0;}
Optimization: first store the number of M groups in arrays, and then only store the root nodes of these nodes.
Initial Value Fa [U [I] = U [I]; Fa [V [I] = V [I];
Reference code:
#include<stdio.h>int fa[1000],u[1000],v[1000];int find(int u){ return fa[u]==u?u:fa[u]=find(fa[u]);}int main(){ int i,n,m,x,y; scanf("%d%d",&n,&m); while (n) { for (i=1;i<=m;i++) { scanf("%d%d",&u[i],&v[i]); fa[u[i]]=u[i]; fa[v[i]]=v[i]; } for (i=1;i<=m;i++) { x=find(u[i]);y=find(v[i]); if (x!=y) { fa[x]=y; n--; } } n--; printf("%d\n",n); scanf("%d%d",&n,&m); } return 0;}