【2018工研】求交集并集(set的用法)

27 篇文章 2 订阅
6 篇文章 0 订阅
这篇博客探讨了在处理含有重复元素的集合时,如何计算交集和并集的元素个数。通过两种不同的实现方式,一是使用数组和计数,二是利用set的特性,展示了如何有效地解决这个问题。代码实例详细解释了每一步的操作,强调了去除重复元素的关键步骤。
摘要由CSDN通过智能技术生成

题目

第一题,输入两个集合,分别求其交集和并集中元素的个数,每个集合中可能存在相同的元素,而最终的交集和并集中应该不存在。

输入:

4 5

3 4 7 3

4 6 3 2 6

输出:

2 5

这道题看着简单却花了很长时间,因为除了集合之间有重复,集合内部也有重复,我的处理方法是设立A,B两个数组,A控制集合之间的重复元素,B控制第二个集合内部的重复元素

#include<iostream>
using namespace std;
const int maxn = 10010;
int main() {
	int n, m, x,cnt1=0,cnt2=0;
	int A[maxn] = {}, B[maxn] = {};
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		cin >> x;
		if (A[x] == 0)    
			cnt2++;
		A[x]++;
	}
	for (int j = 0; j < m; j++) {
		cin >> x;
		if (A[x] != 0 && B[x] == 0) {    //和集合1相交且第一次出现在集合2
			cnt1++;
			B[x]++;
		}
		if (B[x] == 0) {
			cnt2++;
			B[x]++;
		}
	}
	cout << cnt1 << " " << cnt2;
	system("pause");
	return 0;
}

 使用set在思维上会简单一些:set内部自动有序且不含重复元素

#include<iostream>
#include<set>
using namespace std;
const int maxn = 110;
int main() {
	set<int> a, b;
	int n, m,x,cnt1=0,cnt2=0;
	int A[maxn] = {};
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		cin >> x;
		a.insert(x);
		if (A[x] == 0)
			cnt1++;
		A[x]++;
	}
	for (int i = 0; i < m; i++) {
		cin >> x;
		b.insert(x);
	}
	set<int>::iterator it;
	for (it = b.begin(); it != b.end(); it++) {
		if (A[*it] != 0)
			cnt2++;
		else
			cnt1++;
	}
	cout << cnt2 << " " << cnt1;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值