Problem Description
Given two integers A, B, determined their intersection, union, and I B set in A.
The input format
of the first conduct an integer n, A represents the number of elements in the set.
The second row of n mutually different integers separated by a space, the element A represents a collection.
A third row integer m, B represents the number of elements in the set.
Fourth row have mutually different m space-separated integer representing the element B is set.
All elements in the collection are integers, n, m within the range int <= 1000.
Output format
of the first row in ascending order of the outputs A, B of the intersection of all the elements.
A second output line in order from small to large, all of the elements B and concentrated.
The third line outputs of all elements in A I B set in ascending order.
Sample input
. 5
1 2 3 4. 5
. 5
2. 8. 6 10. 4
sample output
2. 4
1 2 3 4 10. 5. 6. 8
. 1. 3. 5
sample input
. 4
1 2 3 4
. 3
. 5. 6. 7
sample output
1234 . 6. 7. 5
. 1. 4. 3 2
Problem-solving ideas:
Method One: Using STL in an orderly set of lookup function to achieve
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
int A[1000] = {0};
int B[1000] = {0};
set<int> a;
set<int> b;
vector<int> inter;
set<int> unio;
vector<int> resi;
int main(){
int m, n;
cin >> m;
for(int i = 0; i < m; i++){
cin >> A[i];
a.insert(A[i]);
}
cin >> n;
for(int i = 0; i < n; i++){
cin >> B[i];
b.insert(B[i]);
}
//交集
set<int>::iterator it;
for(it = a.begin(); it!=a.end(); it++){
if(b.find(*it) != b.end()) inter.push_back(*it);
}
//并集
for(it = a.begin(); it!=a.end(); it++){
unio.insert(*it);
}
for(it = b.begin(); it!=b.end(); it++){
unio.insert(*it);
}
//余集
for(it = a.begin(); it!=a.end(); it++){
if(b.find(*it) == b.end()) resi.push_back(*it);
}
//打印
for(int i = 0; i < inter.size(); i++){
cout << inter[i] << " ";
}
cout << endl;
for(it = unio.begin(); it != unio.end(); it++){
cout << *it << " ";
}
cout << endl;
for(int i = 0; i < resi.size(); i++){
cout << resi[i] << " ";
}
cout << endl;
return 0;
}
Method 2: Using built-solving function
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
vector<int> a;
vector<int> b;
vector<int> c;
void Print(vector<int> &c){
for(int i=0;i<c.size();i++){
cout<<c[i]<<" ";
}
c.clear();
cout<<endl;
}
int main(){
int m, n, temp;
cin >> m;
for(int i = 0; i < m; i++){
cin >> temp;
a.push_back(temp);
}
sort(a.begin(),a.end());
cin >> n;
for(int i = 0; i < n; i++){
cin >> temp;
b.push_back(temp);
}
sort(b.begin(),b.end());
set_intersection(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));
Print(c);
set_union(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));
Print(c);
set_difference(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));
Print(c);
}