This question is also a standard question and can be found.
After the operation is completed and the set is queried, the number of elements in the same set as the 0 node is queried.
Note that in this operation, you need to first find the parent node 0, and then find the number of parent nodes and the parent node 0 are the same.
At this time, you need to use the find parent operation for each node, because the node's parent is not necessarily the root node of this set at the final state.
#include <stdio.h>const int MAX_N = 30001;struct SubSet{int p, rank;}sub[MAX_N];int N, M;void initSub(){for (int i = 0; i < N; i++){sub[i].p = i;sub[i].rank = 0;}}int find(int x){if (x != sub[x].p) sub[x].p = find(sub[x].p);return sub[x].p;}void unionTwo(int x, int y){int xroot = find(x);int yroot = find(y);if (sub[xroot].rank < sub[yroot].rank) sub[xroot].p = yroot;else{if (sub[xroot].rank == sub[yroot].rank) sub[xroot].rank++;sub[yroot].p = xroot;}}int main(){int a, b, k;while (scanf("%d %d", &N, &M) && (N || M)){initSub();for (int i = 0; i < M; i++){scanf("%d", &k);if (k > 0) scanf("%d", &a);for (int j = 1; j < k; j++){scanf("%d", &b);unionTwo(a, b);}}int sus = 1, p = find(0);for (int i = 1; i < N; i++){if (find(i) == p) sus++;}printf("%d\n", sus);}return 0;}