题目:
{A} + {B}
给你两个集合,要求{A} + {B}.
注:同一个集合中不会有两个相同的元素.
Input
每组输入数据分为三行,第一行有两个数字n,m(0<n,m<=10000),分别表示集合A和集合B的元素个数.后两行分别表示集合A和集合B.每个元素为不超出int范围的整数,每个元素之间有一个空格隔开.
Output
针对每组数据输出一行数据,表示合并后的集合,要求从小到大输出,每个元素之间有一个空格隔开.
Sample Input
1 2 1 2 3 1 2 1 1 2
Sample Output
1 2 3 1 2
涉及知识点:
1、用sort函数快速去重
2、set函数的简单使用
题解1:
利用数组的知识可以较简单地完成此题。首先,此题要求合并两个数组,可以直接把两个数组装到一个数组里,这就在某种意义上完成了合并。接着,利用sort函数完成排序。最后利用sort函数的特性(从小到大排序,相同地数会挨着排列),将不重复的数输出。(与set函数(容器)不同的是,sort不能将数组中重复的元素删除)
代码实现:
#include <cstdio>
#include <algorithm>
using namespace std;
int a[20010];
int main()
{
int n, m, i;
while(~scanf("%d %d", &n, &m))
{
for(i = 0; i < n + m; i ++ ) scanf("%d", &a[i]);
sort(a, a + n + m);
printf("%d", a[0]);
for(i = 1; i < n + m; i ++ )
if(a[i] != a[i - 1]) printf(" %d", a[i]);
puts("");
}
return 0;
}
题解2:
利用set函数(容器)放入、输出即可。
代码实现:
#include <cstdio>
#include <set>
using namespace std;
int main()
{
int n, m, i, tmp;
set<int> s;
while(~scanf("%d %d", &n, &m))
{
for(i = 0; i < n + m; i ++ ) //此段是将元素放入set容器的模板
{
scanf("%d", &tmp);
s.insert(tmp);
}
while(!s.empty())
{
printf("%d", *s.begin());
if(s.size() != 1) printf(" "); //判断set容器是否剩最后一个,从而判断是否打印空格
s.erase(s.begin()); //删除第一个元素
}
puts("");
}
return 0;
}