并查集。
#include#include using namespace std;const int maxn = 55555;int fa[maxn];int vis[maxn];int n,m,t;void init(){ for(int i = 0; i < n; i++) {fa[i] = i;} memset(vis,0,sizeof(vis));}int find_father(int u){ return fa[u] == u ? u : fa[u] = find_father(fa[u]);}int main(){ int Case = 1; while(scanf("%d%d",&n,&m)){ if(!m && !n) break; init(); for(int i = 0; i < m; i++){ int x,y; scanf("%d%d",&x,&y); int fx = find_father(x); int fy = find_father(y); fa[fx] = fy; } int cnt = 0; for(int i = 1; i <= n; i++){ int t = find_father(i); if(!vis[t]){ vis[t] = 1; cnt ++; } } printf("Case %d: %d\n",Case++,cnt); } return 0;}