题目:
集合的交集和并集
原题链接:
https://www.acwing.com/problem/content/3691/
set:
自动从小到大排序了
//定义
set<int> s1;
//插入
s1.insert(x);
//删除
s1.erase(x);
//循环输出
for(auto i=s1.begin();i!=s1.end();i++)
cout<<*i<<" ";
unordered_map:
//定义
unordered_map<char, int> ma;
//添加
ma[x] = y;//ma[键]=值;
//查找元素
map<char,int>::iterator it = mp.find('b');
printf("%c %d\n",it -> first,it -> second);
//删除
map<char,int>::iterator it = mp.find('b');
mp.erase(it);
//或者也可以这样删除
mp.erase('b');
//循环输出
for(map<char,int>::iterator it= mp.begin();it != mp.end();it++)
{
cout<<it -> first<<" "<<it -> second;
}
本题代码:
//TLE了
#include<bits/stdc++.h>
using namespace std;
set<int> m1,m2;
int a,b;
set<int> New;
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
int x; cin>>x;
m1.insert(x);
}
for(int i=1;i<=m;i++){
int x; cin>>x;
m2.insert(x);
}
for(auto i=m1.begin();i!=m1.end();i++)
for(auto j=m2.begin();j!=m2.end();j++)
{
if(*i==*j)
a++;
}
cout<<a<<" ";
for(auto i=m1.begin();i!=m1.end();i++)
New.insert(*i);
for(auto j=m2.begin();j!=m2.end();j++)
New.insert(*j);
cout<<New.size();
return 0;
}
//AC
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int a[N],b[N];
map<int ,int > ma; //用map就行了
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
ma[x]=1;
}
for(int i=0;i<m;i++)
{
int x;
cin>>x;
if(ma[x]>0)
ma[x]=2;
else
ma[x]=0;//这里设置成非1的数字,防止将B集合中重复出现、但A集合没出现的算在里面
}
int a=0,b=0;
for(auto item:ma)
{
//cout<<item.first<<":"<<item.second<<endl;
if(item.second==2)
b++;
}
cout<<b<<" "<<ma.size()<<endl;
return 0;
}