1063. Set Similarity

给出n个集合和k次查询, 计算集合相似度:

集合相似度 = 交集元素数量 / 并集元素数量

思路: 重复查询缓存结果

tips:

  • C++ STL中有set_intersection, set_union, set_difference可以直接使用
  • insert_iterator(Container container, Iterator iter)可以创建一个"自动插入迭代器", 将对迭代器的copy(to)操作转化为插入操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <map>
#include <set>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
using namespace std;


set<int> S[50];
float F[50][50];

float compare(int _a, int _b)
{
if (F[_a][_b]) {
return F[_a][_b];
}
set<int> &a = S[_a], &b = S[_b];
set<int> U, I;
set_intersection(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int>>(I, I.begin()));
set_union(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int>>(U, U.begin()));
float res = static_cast<float>(I.size()) / U.size();
if (res == 0) res = 0.0001F;
return F[_a][_b] = F[_b][_a] = res;
}

int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int s;
cin >> s;
for (int j = 0; j < s; j++) {
int x;
cin >> x;
S[i].insert(x);
}
}

int k;
cin >> k;
for (int i = 0; i < k; i++) {
int a, b;
cin >> a >> b;
printf("%.1f%%\n", 100 * compare(a - 1, b - 1));
}

return 0;
}