1063 Set Similarity (25分)
Given two sets of integers, the similarity of the sets is defined to be Nc /Nt ×100%, where Nc is the number of distinct common numbers shared by the two sets, and Nt is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.
选择用的unorderuned_set去重复元素,再将两组数据的元素进行比较。
set 与unorderuned_set区别:
set基于红黑树实现,红黑树具有自动排序的功能,因此map内部所有的数据,在任何时候,都是有序的。
unordered_set基于哈希表,数据插入和查找的时间复杂度很低,几乎是常数时间,而代价是消耗比较多的内存,无自动排序功能。底层实现上,使用一个下标范围比较大的数组来存储元素,形成很多的桶,利用hash函数对key进行映射到不同区域进行保存。
AC代码
#include <iostream>
#include <cstdio>
#include <unordered_set>
using namespace std;
int n,m,k,x,y;
const int INF=0x7fffffff;
unordered_set<int> nums[51];
double dp[51][51];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&m);
for(int j=0;j<m;j++){
scanf("%d",&x);
nums[i].insert(x);
}
}
fill(dp[0],dp[0]+51*51,sizeof(dp));
scanf("%d",&k);
for(int i=0;i<k;i++){
scanf("%d%d",&x,&y);
if(dp[x][y]!=INF||dp[y][x]!=INF){
int cnt=0;
for(unordered_set<int>::iterator it=nums[x].begin();it!=nums[x].end();it++){
if(nums[y].find(*it)!=nums[y].end())
cnt++;
}
dp[x][y]=(double)100*cnt/(nums[x].size()+nums[y].size()-cnt);
dp[y][x]=dp[x][y];
printf("%.1f%%\n",dp[x][y]);
}
else{
printf("%.1f%%\n",dp[x][y]);
}
}
return 0;
}
疑问:一开始两组元素的比较我采取的方法是将x组的元素记录在map中,遍历y组时去查map,但是结果却超时,书上说set的find函数时间复杂度是logN,AC的代码却可以这个却不可以。。代码如下:
unordered_map<int,bool> mp;
for(unordered_set<int>::iterator it=nums[x].begin();it!=nums[x].end();it++){
mp[*it]=true;
}
int cnt=0;
for(unordered_set<int>::iterator it2=nums[y].begin();it2!=nums[y].end();it2++){
if(mp[*it2])
cnt++;
}
最后比较一下set 与unordered_set的速度
使用unordered_set:
最后一个测试点为90ms
使用set:
181ms