L2-005. 集合相似度
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定两个整数集合,它们的相似度定义为: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%
/*思路:要用到stl里的set,然后在另一个集合中遍历是否含有本集合的元素,有的话计数器+1;最后用相同元素个数除以两个集合元素的总个数
减去相同元素个数就是答案*/
#include<iostream> #include<set> using namespace std; double Check(set<int> p, set<int> q) { double count1 = p.size() + q.size(); double outcome; double count2 = 0; set<int>::iterator iter; for (iter = p.begin();iter != p.end();iter++) { if (q.count((*iter)) == 1)//判断在集合2中是否含有集合1中遍历的元素 count2++; } outcome = count2 / (count1 - count2); return outcome; } int main() { int N; cin >> N; int count; int num; int set1, set2; double analogy; set<int> *p = new set<int>[N+1]; for (int i = 1;i < N+1;i++) { cin >> count; for (int q = 0;q < count;q++) { cin >> num; p[i].insert(num); } } int seanum; cin >> seanum; double *check = new double[seanum]; for(int m = 0;m < seanum;m++) { cin >> set1; cin >> set2; check[m] = Check(p[set1], p[set2]); } for (int i = 0;i < seanum;i++) printf("%.2f%%\n", check[i]*100); system("PAUSE"); return 0; }