这里用一下 set_intersaction()函数来计算交集

set_intersection()作用是求两个集合的交集:

其中有5个参数:firts1,last1,first2,last2,result。
他们都是迭代器。需要注意的是,所求的两个集合必须是有序的,不然运行时会出现错误。
例子

set_intersection(nums1.begin(), nums1.end(), nums2.begin(),nums2.end(),inserter(re,re.begin()));

这里要注意加inserter可能是新加的C++特性,最后一个参数写re.begin会报错。

set_union同理。

并且使用字符串hash加快处理速度

#pragma GCC optimize(2, 3, "Ofast", "inline")
#include <bits/stdc++.h>
using namespace std;
set<int> a;
set<int> b;
unsigned int BKDRHash(string str)
{
    unsigned int seed = 131; // 31 131 1313 13131 131313等质数
    unsigned int hash = 0;
    for(int i=0;i<str.size();i++) 
    {
        hash = hash * seed + (str[i]);
    }
    return (hash & 0x7FFFFFFF);
}
string tolow(string str)
{
	for(int i=0;i<str.length();i++){
		str[i]=tolower(str[i]);   
	}
    return str;
}
void work()
{
    int n,m;
    cin>>n>>m;
    set<int> c1;
    set<int> c2;
    string s1;
    for(int i=0;i<n;i++)
    {
        cin>>s1;
        a.insert(BKDRHash(tolow(s1)));
    }
    for(int i=0;i<m;i++)
    {
        cin>>s1;
        b.insert(BKDRHash(tolow(s1)));
    }
    
    // inserter(c,c.begin())为插入迭代器,不能直接用c.begin()会报错
    set_intersection(a.begin(),a.end(),b.begin(),b.end(),inserter(c1,c1.begin()));
    set_union(a.begin(),a.end(),b.begin(),b.end(),inserter(c2,c2.begin()));
    cout<<c1.size()<<endl;
    cout<<c2.size();
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    work();
    return 0;
}

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐