ou_fan
给你两个集合,计算其并集,即{A}+{B}。
注意:{A}+{B}中不允许出现重复元素,但是{A}与{B}之间可能存在相同的元素。
输入格式
输入数据分为三行,第一行有两个数字n,m(0<n,m<10000),分别表示集合A和集合B的元素个数。后两行分别表示集合{A}和集合{B}。每个元素为不超过int范围的整数,每个元素之间用空格隔开。
输出格式
输出一行数据,表示合并后的集合,要求从小到大输出,每个元素之间用一个空格隔开。
样例输入1
1 2
1
2 3
样例输出1
1 2 3样例输入2
1 2
1
1 2
样例输出2
1 2
分析:集合问题又要从小到大排序,且需要去重,所以使用set容器;
#include<bits/stdc++.h>
using namespace std;
set<int>arr;
int main() {
int n, m;
cin >> n >> m;
//首先将第一个集合读入set
for (int i = 0;i < n;i++) {
int num;
cin >> num;
arr.insert(num);
}
//第二个集合,先查找有没有,再插入进去。
for (int i = 0;i < m;i++) {
int num;
cin >> num;
if (arr.count(num)) continue;
else arr.insert(num);
}
for (auto it = arr.begin();it != arr.end();it++) {
if (it != arr.begin()) cout << ' ';
cout << *it;
}
return 0;
}
反思:set会自动查重,所以不用做判断;
简便代码:
#include<bits/stdc++.h>
using namespace std;
set<int>arr;
int main() {
int n, m;
cin >> n >> m;
//首先将第一个集合读入set
for (int i = 0;i < n+m;i++) {
int num;
cin >> num;
arr.insert(num);
}
for (auto it = arr.begin();it != arr.end();it++) {
if (it != arr.begin()) cout << ' ';
cout << *it;
}
return 0;
}