题目
第一题,输入两个集合,分别求其交集和并集中元素的个数,每个集合中可能存在相同的元素,而最终的交集和并集中应该不存在。
输入:
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;
}