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.
Input Specification:
Each input file contains one test case. Each case first gives a positive integer N (<=50) which is the total number of sets. Then N lines follow, each gives a set with a positive M (<=104) and followed by M integers in the range [0, 109]. After the input of sets, a positive integer K (<=2000) is given, followed by K lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to N). All the numbers in a line are separated by a space.
Output Specification:
For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.
Sample Input:3 3 99 87 101 4 87 101 5 87 7 99 101 18 5 135 18 99 2 1 2 1 3Sample Output:
50.0% 33.3%
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
using namespace std;
int compare(const void *a,const void *b){
return *(long*)a-*(long*)b;
}
float similarity(long *a,int len_a,long *b,int len_b){
qsort(a,len_a,sizeof(long),compare);
qsort(b,len_b,sizeof(long),compare);
int i=0,j=0;
int sum=0;
int count=0;
while(i<len_a&&j<len_b){
while(i+1<len_a){
if(a[i]==a[i+1]){
i++;
sum++;
}
else
break;
}
while(j+1<len_b){
if(b[j]==b[j+1]){
j++;
sum++;
}
else
break;
}
if(a[i]<b[j])
i++;
else if(a[i]>b[j])
j++;
else{
i++;
j++;
count++;
}
}
float res=count*1.0/(len_a+len_b-sum-count);
return res;
}
int main()
{
int n,i,j;
scanf("%d",&n);
long **num=new long *[n+1];
int *len=new int[n+1];
for(i=1;i<=n;i++){
scanf("%d",&len[i]);
num[i]=new long [len[i]];
for(j=0;j<len[i];j++)
scanf("%ld",&num[i][j]);
}
int k;
scanf("%d",&k);
for(i=0;i<k;i++){
int a,b;
scanf("%d%d",&a,&b);
float sim=similarity(num[a],len[a],num[b],len[b]);
printf("%.1f%%\n",sim*100);
}
return 0;
}

本文介绍了一个计算两个整数集合相似度的方法,通过定义相似度为两集合共有不同元素数量除以总的不同元素数量来衡量集合间的相似性。文章提供了一个具体的输入输出样例,并给出了实现该功能的C++代码。
2356

被折叠的 条评论
为什么被折叠?



