题目
给定两个整数集合,它们的相似度定义为:Nc/Nt×100%。其中Nc是两个集合都有的不相等整数的个数,Nt是两个集合一共有的不相等整数的个数。你的任务就是计算任意一对给定集合的相似度。
输入格式:
输入第一行给出一个正整数N(≤50),是集合的个数。随后N行,每行对应一个集合。每个集合首先给出一个正整数M(≤104),是集合中元素的个数;然后跟M个[0,109]区间内的整数。
之后一行给出一个正整数K(≤2000),随后K行,每行对应一对需要计算相似度的集合的编号(集合从1到N编号)。数字间以空格分隔。
输出格式:
对每一对需要计算的集合,在一行中输出它们的相似度,为保留小数点后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%
解题思路:
思路一:拿到题目第一反应是手写哈希表,但没注意数据范围1e9
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int q[51][N], num[55];//初始化为0
int n, k;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int m;
scanf("%d", &m);
for (int j = 1; j <= m; j++) {
int a;
scanf("%d", &a);
if (a > num[i])
num[i] = a;
q[i][a] = 1; //出现的数字标为1
}
}
scanf("%d", &k);
for (int i = 1; i <= k; i++) {
int x, y;
scanf("%d%d", &x, &y);
int t = max(num[x], num[y]), nc = 0, nt = 0;
for (int i = 1; i <= t; i++) {
if (q[x][i] || q[y][i])
nt++;//q[x][i]或q[y][i]处有数出现过
if (q[x][i] && q[y][i])
nc++;//q[x][i]q[y][i]处都为1
}
double s = 1.0 * nc / nt * 100;
printf("%.2f%%\n", s);
}
return 0;
}
PTA结果:
思路二:看了很多人的思路都是采用c++中封装的set或unordered_set哈希来求解.具体知识可参考:C++中set用法详解_c++ set-CSDN博客
C++ STL unordered_set容器完全攻略 (biancheng.net)
其中使用unorder_set的ac代码如下:
#include <bits/stdc++.h>
#include <unordered_set>
using namespace std;
const int N = 60;
unordered_set<int> q[N];
int n, m, k;
int main() {
cin >> n;
for (int i = 1; i <= n; i ++ ) {
cin >> m;
for (int j = 1; j <= m; j++) {
int t;
cin >> t;
q[i].insert(t);
}
}
cin >> k;
while (k--) {
int a, b;
cin >> a >> b;
int nt = 0, nc = 0;
for (auto x : q[a])
if (q[b].count(x))
nc++;
nt = q[a].size() + q[b].size() - nc;
printf("%.2f%%\n", 1.0 * nc / nt * 100);
}
return 0;
}
其他思路可参考:7-9 集合相似度-CSDN博客
编程小白,有不足希望大佬们多多指点!也欢迎大家讨论其他写法