Loading

1063 Set Similarity (25 分)

1. 题目

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 (≤10^4) and followed by M integers in the range [0,10^9]. 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%

2. 题意

有n个set,计算其中两个set的相似度。

相似度=Nc/Nt×100%,Nc为是两个set中共同数字的数量,Nt为两个set整合后的长度。

3. 思路——set

  1. 首先输入n个set
  2. 输入两个set的编号,计算这两个set的相似度。遍历其中一个set,并使用set.count(num)方法找出在另一个数组中也存在的数字,并计数,计数结果即为两个set共同数字的数量。两个set整合后的长度即为两个原set的长度相加,减去计数结果。至此,即可计算两个set的相似度。

4. 代码

#include <iostream>
#include <set>

using namespace std;

int main()
{
	int n;
	scanf("%d", &n);
	set<int> nums[n + 1];
	for (int i = 1; i <= n; ++i)
	{
		int m;
		scanf("%d", &m);
		for (int j = 0; j < m; ++j)
		{
			int x;
			scanf("%d", &x);
			nums[i].insert(x);
		}
	}
	int k;
	scanf("%d", &k);
	while (k--)
	{
		int x, y;
		scanf("%d%d", &x, &y);
		int cnt = 0;
		for (auto a: nums[x])	// 计算两个set中相同数字的数量 
			if (nums[y].count(a)) cnt++;
		// 两个set整合为一个set的数量为:
		// 两个set原数量之和 - 两个set中相同数字的数量 
		int total = nums[x].size() + nums[y].size() - cnt;
		printf("%.1lf%%\n", 100.0 * cnt / total);
	} 
	return 0;
}
posted @ 2021-10-29 12:46  August_丶  阅读(36)  评论(0编辑  收藏  举报