题目背景
两个集合的 Jaccard 相似度定义为:Sim(A,B)=∣A∩B∣∣A∪B∣Sim(A,B)=∣A∪B∣∣A∩B∣即交集的大小除以并集的大小。当集合 AA 和 BB 完全相同时,Sim(A,B)=1Sim(A,B)=1 取得最大值;当二者交集为空时,Sim(A,B)=0Sim(A,B)=0 取得最小值。
题目描述
除了进行简单的词频统计,小 P 还希望使用 Jaccard 相似度来评估两篇文章的相似性。 具体来说,每篇文章均由若干个英文单词组成,且英文单词仅包含“大小写英文字母”。 对于给定的两篇文章,小 P 首先需要提取出两者的单词集合 AA 和 BB,即去掉各自重复的单词。 然后计算出:
- ∣A∩B∣∣A∩B∣,即有多少个不同的单词同时出现在两篇文章中;
- ∣A∪B∣∣A∪B∣,即两篇文章一共包含了多少个不同的单词。
最后再将两者相除即可算出相似度。 需要注意,在整个计算过程中应当忽略英文字母大小写的区别,比如 the
、The
和 THE
三者都应被视作同一个单词。
试编写程序帮助小 P 完成前两步,计算出 ∣A∩B∣∣A∩B∣ 和 ∣A∪B∣∣A∪B∣;小 P 将亲自完成最后一步的除法运算。
输入格式
从标准输入读入数据。
输入共三行。
输入的第一行包含两个正整数 nn 和 mm,分别表示两篇文章的单词个数。
第二行包含空格分隔的 nn 个单词,表示第一篇文章;
第三行包含空格分隔的 mm 个单词,表示第二篇文章。
输出格式
输出到标准输出。
输出共两行。
第一行输出一个整数 ∣A∩B∣∣A∩B∣,即有多少个不同的单词同时出现在两篇文章中;
第二行输出一个整数 ∣A∪B∣∣A∪B∣,即两篇文章一共包含了多少个不同的单词。
样例1输入
3 2
The tHe thE
the THE
样例1输出
1
1
样例1解释
A=B=A∩B=A∪B=A=B=A∩B=A∪B= {the}
样例2输入
9 7
Par les soirs bleus dete jirai dans les sentiers
PICOTE PAR LES BLES FOULER LHERBE MENUE
样例2输出
2
13
样例2解释
A=A= {bleus, dans, dete, jirai, les, par, sentiers, soirs}
∣A∣=8∣A∣=8
B=B= {bles, fouler, les, lherbe, menue, par, picote}
∣B∣=7∣B∣=7
A∩B=A∩B= {les, par}
∣A∩B∣=2∣A∩B∣=2
样例3输入
15 15
Thou that art now the worlds fresh ornament And only herald to the gaudy spring
Shall I compare thee to a summers day Thou art more lovely and more temperate
样例3输出
4
24
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
set<string>article1;
set<string>article2;
for(int i=0;i<n;i++){
string word;
cin>>word;
article1.insert(word);
}
for(int j=0;j<m;j++){
string word;
cin>>word;
article2.insert(word);
}
vector<string>intersection_result;
set_intersection(
article1.begin(),article1.end(),
article2.begin(),article2.end(),back_inserter(intersection_result));
int result1 = intersection_result.size();
vector<string>union_result;
set_union(article1.begin(),article1.end(),
article2.begin(),article2.end(),back_inserter(union_result));
int result2=union_result.size();
cout<<result1<<endl;
cout<<result2<<endl;
return 0;
}