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 Nlines 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 3
Sample Output:
50.0%
33.3%
题意分析:注意理解nt,要的是两个set中不重复的数,相当于将两个set放进一个set中,即把重复的数去掉。只留下两组数中不重复的,而不是求两组中不相同的数。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <set>
using namespace std;
int main()
{
//freopen("in.txt", "r", stdin);
int n;
scanf("%d", &n);
vector<set<int>> v(n + 1);
for (int i = 1; i <= n; i++)
{
int m,temp;
set<int> s;
scanf("%d", &m);
for (int j = 0; j < m; j++)
{
scanf("%d", &temp);
s.insert(temp);
}
v[i] = s;
}
int k;
scanf("%d", &k);
for (int i = 0; i <k; i++)
{
int a, b;
scanf("%d %d", &a, &b);
int nc = 0, nt = v[b].size();
for (auto it=v[a].begin();it!=v[a].end();it++)
{
if (v[b].find(*it) == v[b].end())
{
nt++;
}
else
{
nc++;
}
}
double ans = (double)nc / nt*100;
printf("%.1f%%\n", ans); // 基本功 %的输出 :要用两个百分号
}
//fclose(stdin);
return 0;
}
本文介绍了一种计算两个整数集合相似度的方法,定义为两集合共同元素数量与总不重复元素数量的比例。通过输入多个集合并进行配对查询,演示了如何使用C++实现这一算法,包括读取数据、存储集合、计算相似度等步骤。

1925

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



