PTAL2-005 集合相似度解题报告---set查找

版权声明:转载请注明出处:https://blog.csdn.net/qq1013459920 https://blog.csdn.net/qq1013459920/article/details/85123543

                                   L2-005 集合相似度 (25 分)

给定两个整数集合,它们的相似度定义为:N​c​​/N​t​​×100%。其中N​c​​是两个集合都有的不相等整数的个数,N​t​​是两个集合一共有的不相等整数的个数。你的任务就是计算任意一对给定集合的相似度。

输入格式:

输入第一行给出一个正整数N(≤50),是集合的个数。随后N行,每行对应一个集合。每个集合首先给出一个正整数M(≤10​4​​),是集合中元素的个数;然后跟M个[0,10​9​​]区间内的整数。

之后一行给出一个正整数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%

不用STL的话这个题拿满分就比较麻烦了,要自己写一颗二叉树或或者进行数组排序后二分查找

STL中的set基于二叉树实现,自带搜索find函数,解决最后一个测试点超时的情况

 AC Code:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<string>
#include<cctype>
#include<map>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#define INF 0x3f3f3f3f
using namespace std;
static const int MAX_N = 1e5 + 5;
typedef long long ll;
set<int> S[55];
int main(){
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		int m;
		scanf("%d", &m);
		for (int j = 0; j < m; j++) {
			int v1;
			scanf("%d", &v1);
			S[i].insert(v1);	//加入集合(自动去重)
		}
	}
	int q;
	scanf("%d", &q);
	while (q--) {
		int c1, c2;
		scanf("%d%d", &c1, &c2);
		c1--; c2--;
		int nc = S[c1].size(), nt = S[c1].size() + S[c2].size();
		for (set<int>::iterator it = S[c1].begin(); it != S[c1].end(); it++) {
			if (S[c2].find(*it) != S[c2].end()) nt--;	//find二叉树搜索
			else nc--;
		}
		printf("%.2f%%\n", 1.0 * nc / nt * 100);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq1013459920/article/details/85123543