问题描述
给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集。
输入格式
第一行为一个整数n,表示集合A中的元素个数。
第二行有n个互不相同的用空格隔开的整数,表示集合A中的元素。
第三行为一个整数m,表示集合B中的元素个数。
第四行有m个互不相同的用空格隔开的整数,表示集合B中的元素。
集合中的所有元素均为int范围内的整数,n、m<=1000。
输出格式
第一行按从小到大的顺序输出A、B交集中的所有元素。
第二行按从小到大的顺序输出A、B并集中的所有元素。
第三行按从小到大的顺序输出B在A中的余集中的所有元素。
样例输入
5
1 2 3 4 5
5
2 4 6 8 10
样例输出
2 4
1 2 3 4 5 6 8 10
1 3 5
样例输入
4
1 2 3 4
3
5 6 7
样例输出
1 2 3 4 5 6 7
1 2 3 4
题解:
思路:用map记录两个集合的数的出现次数
**求并集:**只要出现了的数就可以加进来
**求交集:**出现了两次的数加进来
求B对A的余集: A有B没有的(实际上就是A的减去AB的交集),我这里还是用的map,A集合出现的数+1,B集合也出现了的数-1,最后把次数为1的数加进来。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n,m;
vector <int> A,B;
vector <int> r1,r2,r3;// 交集r1、并集r2、B对A的余集(A有B没有的)r3
map <int,int> mp;
int main()
{
cin >> n;
int x;
for(int i = 0; i < n; i++)
{
cin >> x;
A.push_back(x);
mp[x]++;
}
cin >> m;
for(int i = 0; i < m; i++)
{
cin >> x;
B.push_back(x);
mp[x]++;
}
for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
{
r2.push_back(it->first);// 求并集
if(it->second == 2)
{
r1.push_back(it->first);// 求交集
}
}
mp.clear();
for(int i = 0; i < n; i++)
{
mp[A[i]]++;
}
for(int i = 0; i < m; i++)
{
mp[B[i]]--;
}
for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
{
if(it->second == 1)
{
r3.push_back(it->first);
}
}
if((int)r1.size() != 0)
{
for(int i = 0; i < (int)r1.size(); i++)
{
cout << r1[i] << " ";
}
cout << endl;
}
if((int)r2.size() != 0)
{
for(int i = 0; i < (int)r2.size(); i++)
{
cout << r2[i] << " ";
}
cout << endl;
}
if((int)r3.size() != 0)
{
for(int i = 0; i < (int)r3.size(); i++)
{
cout << r3[i] << " ";
}
cout << endl;
}
return 0;
}