将节点进行初始化,然后每加入一条边就建立连接,最后的连通分量个数就是不同集合的个数,而不同集合的个数就是根节点不变(初始化本身)的个数。 #include <cstdio> using namespace std; const int MAXN = 1000; int father[MAXN]; int height[MAXN]; void Initial(int n ){ for (int i = 0; i < n; ++i) { father[i] = i; height[i] = 0; } } int Find(int x){ if (x!=father[x]){ father[x] = Find(father[x]); } return father[x]; } void Union(int x,int y){ x=Find(x); y = Find(y); if (x!=y){ if (height[x] < height[y]){ father[x] = y; } else if(height[x] > height[y]){ father[y] = x; } else { father[y] = x; height[x]++; } } } /*输入n个节点,m条边,记连通分量个数为component */ int main(){ int n,m; while (scanf(" %d%d",&n,&m)!=EOF){ if (n==0){ break; } Initial(n); while (m--){ int x,y; scanf("%d%d",&x,&y); Union(x,y); } int component = 0; for (int i = 1; i <= n; ++i) { if (i==Find(i)){ component++; } } if (component==1){ printf("YES\n"); }else{ printf("NO\n"); } } return 0; }