我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED
原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805409175420928
题目描述:
题目翻译:
1063 集合相似度
给定两组整数,集合的相似性定义为Nc / Nt * 100%,其中Nc是两组共享的不同公共数的数量,和Nt是两组中不同数字的总数。 你的任务是计算给定的任意一组数的相似度。
输入格式:
每个输入文件包含一个测试用例。每个案例首先给出正整数N(<= 50),这是集合的总数。然后是N行,每行给出一个正数M(<= 10),紧跟着M个[0, 10 ^ 9]范围内的整数。在输入集合之后,给出正整数K(<= 2000),然后是K行查询。每个查询给出一对集合编号(集合从1到N编号)。一行中的所有数字都用空格分隔。
输出格式:
对于每个查询,在一行中打印集合的相似度,以百分比形式精确到小数点后1位。
输入样例:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3
输出样例:
50.0%
33.3%
知识点:set集合的应用
思路:用set集合存储各组数据
时间复杂度与查询的组号以及每组集合中的不同元素个数有关。空间复杂度也与每组集合中的不同元素个数有关。
C++代码:
#include<iostream>
#include<set>
#include<algorithm>
using namespace std;
int main(){
int N, M, num, K, num1, num2, Nc, Nt;
scanf("%d", &N);
set<int> nums[N + 1];
set<int>::iterator it;
for(int i = 1; i <= N; i++){
scanf("%d", &M);
for(int j = 0; j < M; j++){
scanf("%d", &num);
nums[i].insert(num);
}
}
scanf("%d", &K);
for(int i = 0; i < K; i++){
Nc = 0;
scanf("%d %d", &num1, &num2);
for(it = nums[num1].begin(); it != nums[num1].end(); it++){
if(nums[num2].find(*it) != nums[num2].end()){
Nc++;
}
}
Nt = nums[num1].size() + nums[num2].size() - Nc;
printf("%.1f%\n", Nc * 100.0 / Nt);
}
}
C++解题报告: