PAT 1063. Set Similarity (25)

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 (<=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%

把数据放到set当中,由于set是有序的并且是值是唯一的,所以可以很方便的求出两个集合的集合度

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
#include <cstdio>
#include <set>
#include <vector>

using namespace std;

double simulate_rate(const set<int> &a, const set<int> &b) {
int cnt = 0;
auto i = a.begin(), j = b.begin();
while (i != a.end() && j != b.end()) {
if (*i == *j) {
cnt++;
i++;
j++;

} else if (*i < *j) {
i++;

} else {
j++;

}

}

return cnt * 100.0 / (a.size() + b.size() - cnt);
}

int main() {
int n = 0, m = 0, t = 0, k = 0, a = 0, b = 0;
scanf("%d", &n);
vector<set<int>> v(n + 1);
for (int i = 1; i <= n; i++) {
scanf("%d", &m);
for (int j = 0; j < m; j++) {
scanf("%d", &t);
v[i].insert(t);

}

}
scanf("%d", &k);
for (int i = 0; i < k; i++) {
scanf("%d %d", &a, &b);
printf("%.2f%%\n", simulate_rate(v[a], v[b]));

}
return 0;
}