7-9 集合的“交”与“并” (20分)
给出两个由数字组成的集合,请求这两个集合的“交”和“并”。
输入格式:
给一个n,m 代表两个数列的大小 (0 <= n,m <=2e5)
如果n>0,则接下来一行, n个数空格隔开,代表第一个集合中的数。
如果m>0,则接下来一行, m个数空格隔开,代表第二个集合中的数。
-1e9<=ai,bi<=1e9
输出格式:
第一行首先输出两个数列交的集合中元素个数,如果元素个数大于0,则紧接着在这行输出“交集”的元素,按数值大小升序排列(本行输出多个数据时,用空格隔开,如果只有一个元素个数,行末无空格)
第二行首先输出两个数列并的集合中元素个数,如果元素个数大于0,则紧接着在这行输出“并集”的元素,按数值大小升序排列(本行输出多个数据时,用空格隔开,如果只有一个元素个数,行末无空格)
输入样例1:
1 3
1
1 3 4
输出样例1:
1 1
3 1 3 4
输入样例2:
1 3
1
2 3 4
输出样例2:
0
4 1 2 3 4
set
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<vector>
#include<iomanip>
#include<iostream>
#include<cstring>
#include <list>
#include<set>
#include<functional>
using namespace std;
typedef long long ll;
#define ture true
#define flase false
int main()
{
int n,m,a,i;
string s,name;
cin>>n>>m;
set<int> s1;
set<int> s2;
set<int>s3;
s1.clear();
s2.clear();
for(i=0;i<n;i++){
cin>>a;
s1.insert(a);
}
for(i=0;i<m;i++){
cin>>a;
s2.insert(a);
}
s3.clear();
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),inserter(s3,s3.begin()));
cout<<s3.size();
for(auto it =s3.begin();it!=s3.end();it++){
cout<<" "<<*it;
}
cout<<endl;
s3.clear();
set_union(s1.begin(),s1.end(),s2.begin(),s2.end(), inserter(s3,s3.begin()));
cout<<s3.size();
for(auto it =s3.begin();it!=s3.end();it++){
cout<<" "<<*it;
}
cout<<endl;
return 0;
}