求合集合的程序可以根据不同的数据结构和编程语言有不同的实现方法。以下是几种常见编程语言的集合求合程序示例:
C++ 示例
使用并查集(Union-Find)数据结构
```cpp
include include using namespace std; const int N = 100010; int p[N]; int find(int x) { if (p[x] != x) p[x] = find(p[x]); return p[x]; } void unionSet(int a, int b) { p[find(a)] = find(b); } int main() { int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) p[i] = i; while (m--) { char op; int a, b; cin >> op >> a >> b; if (op == 'M') { unionSet(a, b); } else { if (find(a) == find(b)) { cout << "Yes" << endl; } else { cout << "No" << endl; } } } return 0; } ``` Python 示例 使用集合(set)数据结构 ```python def union_sets(set1, set2): return set1.union(set2) 示例输入 n = 5 m = 3 a = [1, 2, 3, 4, 5] b = [4, 5, 6] 示例输出 union_set = union_sets(set(a), set(b)) print(union_set) 输出: {1, 2, 3, 4, 5, 6} ``` Java 示例 使用集合(Set)数据结构 ```java import java.util.HashSet; import java.util.Set; public class UnionSets { public static Set Set result.addAll(set2); return result; } public static void main(String[] args) { // 示例输入 int n = 5; int m = 3; int[] a = {1, 2, 3, 4, 5}; int[] b = {4, 5, 6}; // 示例输出 Set for (int num : a) unionSet.add(num); for (int num : b) unionSet.add(num); System.out.println(unionSet); // 输出: [1, 2, 3, 4, 5, 6] } } ``` C 示例 使用数组和排序