输入格式:
输出格式:
对每一对需要计算的集合,在一行中输出它们的相似度,为保留小数点后2位的百分比数字。
输入样例:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3输出样例:
50.00%
33.33%
#include <iostream>
#include <set>
using namespace std;
int main()
{
int n, m, k, temp; cin >> n;
set<int> num[60];
for (int i = 1; i <= n; i++) { //n个集合
cin >> m; //该集合m个元素
while (m--) {
cin >> temp;
num[i].insert(temp); //set容器,无法插入相同元素,达到自动去重效果
}
}
cin >> k;
int a, b, nc = 0, nt;
while (k--) {
cin >> a >> b;
for (set<int>::iterator it = num[a].begin(); it != num[a].end(); it++) { //记录交集的元素个数
if (num[b].find(*it) != num[b].end())
nc++;
}
nt = num[a].size() + num[b].size() - nc; //记录并集的元素个数
printf("%.2f%%\n", nc * 1.0 / nt * 100);
nc = 0;
}
return 0;
}
注意事项:
思路很简单,储存每个集合,对指定的两个集合求交集和并集,过程中需要对集合元素去重。C语言且二维数组会段错误......
如有问题,欢迎提出。