给你两个集合,要求{A} + {B}. 同一个集合中不会有两个相同的元素.
Input每组输入数据分为三行,第一行有两个数字n,m(0<n,m<=10000),分别表示集合A和集合B的元素个数.后两行分别表示集合A和集合B.每个元素为不超出int范围的整数,每个元素之间有一个空格隔开.
Output针对每组数据输出一行数据,表示合并后的集合,要求从小到大输出,每个元素之间有一个空格隔开.
Sample Input1 2
1
2 3
1 2
1
1 2
Sample Output
1 2 3
1 2
利用set的性质我们可以便易的解决这道题:1.集合的互异性 2.set容器内元素的有序性。
我们声明一个int类型的集合ans。将输入的数字都加入到ans中,集合的性质决定了其中不存在重复且自动排序,然后依次输出。
通过代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include<cstdio> #include<iostream> #include<set> #include<iterator> using namespace std; set<int> ans; int main() { int n,m; while(cin >> n >> m) { ans.clear(); int N = n + m; int a; while(N --) { cin >> a; ans.insert(a); } int z = 0; for(set<int>::iterator it = ans.begin();it != ans.end();it ++) { if(z) { cout << " "; } else{ z = 1; } cout << *it; } cout << endl; } return 0; } |