集合运算之美

|▌冷眼眸甩不掉的悲伤 提交于 2020-02-08 13:19:48

 算法训练 集合运算  

时间限制:1.0s   内存限制:512.0MB

      

锦囊1

排序后处理。

问题描述

给出两个整数集合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
 

#include <iostream>
#include <set>
using namespace std;
set<int> sa,sb,sc; 
int main(int argc, char** argv) {
	int n,m;
	cin>>n;
	int num;
	for(int i=0;i<n;i++){
		cin>>num;
		sa.insert(num);
		sc.insert(num);
	}		
	cin>>m;
	for(int i=0;i<m;i++){
		cin>>num;
		sb.insert(num);
		sc.insert(num);
	}
	for(set<int>::iterator it=sb.begin();it!=sb.end();it++)
		if(sa.count(*it)) cout<<*it<<" ";
	cout<<endl;
	for(set<int>::iterator it=sc.begin();it!=sc.end();it++)
		cout<<*it<<" ";
	cout<<endl;
	for(set<int>::iterator it=sa.begin();it!=sa.end();it++)
		if(!sb.count(*it)) cout<<*it<<" ";
	cout<<endl;
	return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!