并查集基础代码 #include<iostream> #include<string> #include<algorithm> using namespace std; #define N 1000 //元素的上限个数 int father[N]; //存储了每个元素父亲的下标 int height[N]; // 存储了某个根的高度 void Init(int n) { for (int i = 1; i <= n; i++) { father[i] = i; height[i] = 1; } } int Findfather(int x) { if (x != father[x]) { father[x] = Findfather(father[x]); } return father[x]; } void Union(int x, int y,int & num) { x = Findfather(x); y = Findfather(y); if (x != y) { num--; if (height[x] < height[y]) { father[x] = y; } else if (height[x] > height[y]) father[y] = x; else { father[y] = x; ++height[x]; } } } int main() { int n, m; while (cin >> n >> m) { if (n == 0) break; int num = n; Init(n); //初始化并查集 for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; Union(a, b, num); } cout << num-1 << endl; } }