7-4-1 set 集合的“交”与“并” (300分)

7-4-1 set 集合的“交”与“并” (300分)

给出两个由数字组成的集合,请求这两个集合的“交”和“并”。

输入格式:

给一个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

AC

参考链接

https://hbuacm.gitee.io/2020/07/18/day03/

#include<bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    
    
	int n,m;
	set<int> a,b,sa,sb;
	int x;
	cin>>n>>m;
	for(int i=0; i<n; i++) {
    
    
		cin>>x;
		a.insert(x);
	}
	for(int i=0; i<m; i++) {
    
    
		cin>>x;
		b.insert(x);
	}
	set<int>::iterator it;
	//求交集
	for(it=a.begin(); it!=a.end(); it++) {
    
    
		if(b.find(*it)!=b.end())
			sa.insert(*it);
	}
	//求并集
	for(it=a.begin(); it!=a.end(); it++) {
    
    
		sb.insert(*it);
	}
	for(it=b.begin(); it!=b.end(); it++) {
    
    
		sb.insert(*it);
	}
	//输出交集
	cout<<sa.size();
	if(sa.size()!=0) {
    
    
		for(it=sa.begin(); it!=sa.end(); it++)
			cout<<" "<<*it;
	}
	cout<<endl;
	//输出并集
	cout<<sb.size();
	if(sb.size()!=0) {
    
    
		for(it=sb.begin(); it!=sb.end(); it++)
			cout<<" "<<*it;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45745322/article/details/112973874