L2-005 集合相似度 (25 分)
给定两个整数集合,它们的相似度定义为:Nc /Nt×100%。其中Nc是两个集合都有的不相等整数的个数,Nt是两个集合一共有的不相等整数的个数。你的任务就是计算任意一对给定集合的相似度。
输入格式:
输入第一行给出一个正整数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%
【分析】
因为此题求解的两个集合中交集和并集的比值,所有,用数学知识可是,并集的个数等于两个集合自身去重之后的个数 - 两个集合相同的个数,由此,题意就很清晰了,只要用一个set数组把两个集合存起来,在去遍历寻找相同的元素值,最后进行相减就行。。。。
【AC代码】
#include<iostream>
#include<cmath>
#include<cstdio>
#include<string>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<cstring>
#include<set>
using namespace std;
int n;
set<int> u[55];
void f(int a, int b)
{
int same = 0;
set<int>::iterator it;
for (it = u[a].begin(); it != u[a].end(); it++)
{
if (u[b].find(*it) != u[b].end())
{
same++;//用集合a中的值取b中找,如果相同,就++
}
}
int sum = u[a].size() + u[b].size();//这是两个集合中的个数
int nt = sum - same;//并集的个数
printf("%.2lf\%\n", same*1.0 / nt * 100);
}
int main()
{
cin >> n;
int k, a, m;
for (int i = 1; i <= n; i++)
{
cin >> k;
for (int j = 0; j<k; j++)
{
cin >> a;
u[i].insert(a);
}
}
cin >> m;
int b;
for (int i = 0; i<m; i++)
{
cin >> a >> b;
f(a, b);
}
return 0;
}