constint MAX_SIZE = 10001; //unionSet[i] = -1: i 为单个结点 //unionSet[i] = x < -1: i 为根节点,-x 表示树大致的高度 //unionSet[i] = x >= 0: x 是 i 的父节点 int unionSet[MAX_SIZE]; int size;
voidUnion(int elem1, int elem2) { int root1 = Find(elem1); int root2 = Find(elem2); if (root1 == root2) return; int subTree, newRoot; //要把高度低的树挂载到高度高的树上去,从而维护查找结构的平衡 if (unionSet[root1] < unionSet[root2]) { newRoot = root1; subTree = root2; } else { newRoot = root2; subTree = root1; } //挂 unionSet[subTree] = newRoot; //如果原来高度一样,那么新的树高度就会增高 if (unionSet[root1] == unionSet[root2]) unionSet[newRoot]--; }
intmain() { int n, m; ios::sync_with_stdio(false); int z, x, y; while (cin >> n >> m) { //初始化设置,-1 表示初始单个结点的高度为 1 memset(unionSet, -1, sizeof(int) * n); //当Zi=1时,将Xi与Yi所在的集合合并 //当Zi=2时,输出Xi与Yi是否在同一集合内,是的话输出Y;否则话输出N for (int i = 0; i < m; ++i) { cin >> z >> x >> y; if (z == 1) Union(x, y); elseif (z == 2) { if (Find(x) == Find(y)) cout << "Y" << endl; else cout << "N" << endl; } } } return0; }