L2-005 集合相似度

L2-005 集合相似度 (25 分)

给定两个整数集合,它们的相似度定义为:N​c​​/N​t​​×100%。其中N​c​​是两个集合都有的不相等整数的个数,N​t​​是两个集合一共有的不相等整数的个数。你的任务就是计算任意一对给定集合的相似度。

输入格式:

输入第一行给出一个正整数N(≤50),是集合的个数。随后N行,每行对应一个集合。每个集合首先给出一个正整数M(≤10​4​​),是集合中元素的个数;然后跟M个[0,10​9​​]区间内的整数。

之后一行给出一个正整数K(≤2000),随后K行,每行对应一对需要计算相似度的集合的编号(集合从1到N编号)。数字间以空格分隔。

输出格式:

对每一对需要计算的集合,在一行中输出它们的相似度,为保留小数点后2位的百分比数字。

输入样例:

3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3

输出样例:

50.00%
33.33%

思路 

题意很短,所以要看清。

两个集合都有的不相等整数的个数 等价于 两个集合的交集

两个集合一共有的不相等整数的个数 等价于 两个集合的并集

注意:上边说的是集合,但是输入的数据有重复的。

所以用c++就用stl set集合就行了。

第一次写的时候,我是先放在数组中,然后再放到set中进行去重。因为这个数据量 不小,所以最后一组数据超时。

那我们输入的时候就直接放到set中,这样就节省了很多时间

代码

AC的代码

#include<cstdio>
#include<set>
#include<cstring>
#include<algorithm>

using namespace std;

const int maxn = 50 + 5;
set<int> s[maxn];
set<int>::iterator it;

double solve(int p, int q){
	int sum1 = 0;
	int sum2 = 0;
	for(it = s[p].begin(); it != s[p].end(); it++){
		int p = *it;;
		if(s[q].find(p) != s[q].end()){
			sum1++;
		}
	}
	sum2 = s[p].size() + s[q].size() - sum1;
	return (sum1*1.0)/(sum2*1.0)*100;
}

int main(){
	int n,t,p,q;
	scanf("%d",&n);
	for(int i = 1; i <= n; i++){
		scanf("%d",&t);
		for(int j = 1; j <= t; j++){
			int temp;
			scanf("%d",&temp);
			s[i].insert(temp);
		}
	}
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&p,&q);
		printf("%.2lf%%\n",solve(p,q));
		
	}
	return 0;
}

超时的代码

#include<cstdio>
#include<set>
#include<cstring>
#include<algorithm>

using namespace std;

const int maxn = 50 + 5;
int a[maxn][maxn];
set<int> s1,s2;
set<int>::iterator it1;
set<int>::iterator it2;

double solve(int p, int q){
	int sum1 = 0;
	int sum2 = 0;
	s1.clear();
	s2.clear();
	for(int i = 1; i <= a[p][0];i++){
		s1.insert(a[p][i]);
	}
	for(int i = 1; i <= a[q][0];i++){
		s2.insert(a[q][i]);
	}
	for(it1 = s1.begin(); it1 != s1.end(); it1++){
		int p = *it1;;
		if(s2.find(p) != s2.end()){
			sum1++;
		}
	}
	sum2 = s1.size() + s2.size() - sum1;
	return (sum1*1.0)/(sum2*1.0)*100;
}

int main(){
	int n,t,p,q;
	scanf("%d",&n);
	memset(a,-1,sizeof(a));
	for(int i = 1; i <= n; i++){
		scanf("%d",&a[i][0]);
		for(int j = 1; j <= a[i][0] ; j++){
			scanf("%d",&a[i][j]);	
		}
	}
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&p,&q);
		printf("%.2lf%%\n",solve(p,q));
		
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Honyelchak

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值