1063 Set Similarity (25分)

1063 Set Similarity (25分)

Given two sets of integers, the similarity of the sets is defined to be Nc​ /Nt​​ ×100%, where N​c​​ 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值