PAT甲级 1063
题目 Set Similarity
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.
解析
给出n组set集合。从中选两组输出两组,计算:
(两组中数字一样的数量)/(两组数字的总数-两组中数字一样的数量)
代码
#include<bits/stdc++.h>
#define INF 1<<29
using namespace std;
int n, k;
set<int> data[55];
void pat1063() {
cin >> n;
for (int i = 0; i < n; ++i) {
int l;
scanf("%d", &l);
for (int j = 0; j < l; ++j) {
int num;
scanf("%d", &num);
data[i].insert(num);
}
}
cin >> k;
for (int i = 0; i < k; ++i) {
int a, b, temp = 0;
scanf("%d %d", &a, &b);
for (int it : data[a - 1]) {
if (data[b - 1].find(it) != data[b - 1].end()) {
temp++;
}
}
int all = data[a - 1].size() + data[b - 1].size();
float res = (temp * 1.0) / (all - temp) * 100;
printf("%.1f%\n", res);
}
}
int main() {
pat1063();
return 0;
}