Given two sets of integers, the similarity of the sets is defined to be , where is the number of distinct common numbers shared by the two sets, and 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 which is the total number of sets. Then N lines follow, each gives a set with a positive and followed by M integers in the range [0,109]. After the input of sets, a positive integer is given, followed by lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to ). 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%
Ω
求两集合的相似度=交集元素/并集元素。
实际求解过程中只需要求交集元素即可,并集元素数=集合1 +集合2 -交集 。由于C++里面已经支持求交集的函数,可以直接使用,不过用法不是那么好记,当然我们也可以直接用类似归并排序的思想直接实现:
template<class InputIt1, class InputIt2,
class OutputIt, class Compare>
OutputIt set_intersection(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first, Compare comp)
{
while (first1 != last1 && first2 != last2) {
if (comp(*first1, *first2)) {
++first1;
} else {
if (!comp(*first2, *first1)) {
*d_first++ = *first1++; // *first1 and *first2 are equivalent.
}
++first2;
}
}
return d_first;
}
事实上Python中的set容器做的挺好,交并运算都符号化了,实现起来也很快。
🐎
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
int n, m, k;
cin >> n;
set<int> s[n];
for (int i = 0; i < n; ++i)
{
cin >> m;
for (int j = 0; j < m; ++j)
{
cin >> k;
s[i].insert(k);
}
}
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> m >> k;
set<int> inter;
set_intersection(s[m - 1].begin(), s[m - 1].end(), s[k - 1].begin(), s[k - 1].end(),
inserter(inter, inter.begin()));
printf("%.1f%%\n", inter.size() * 1.0 / (s[m - 1].size() + s[k - 1].size() - inter.size()) * 100);
}
}
🐎🐎
num=eval(input())
sets=[set() for i in range(num)]
for i in range(num):
nums=list(map(eval,input().split()))
n=nums[0]
for j in range(n):
m=nums[j+1]
sets[i].add(m)
n=eval(input())
for i in range(n):
a,b=map(eval,input().split())
inter=sets[a-1]&sets[b-1]
print("%.1f%%"%(len(inter)/(len(sets[a-1])+len(sets[b-1])-len(inter))*100))