1063 Set Similarity (25分)

Given two sets of integers, the similarity of the sets is defined to be Nc/Nt×100%, where Nc is the number of distinct common numbers shared by the two sets, and Nt is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.

Input Specification:

Each input file contains one test case. Each case first gives a positive integer N (≤50) which is the total number of sets. Then N lines follow, each gives a set with a positive M (≤104) and followed by M integers in the range [0,109]. After the input of sets, a positive integer K (≤2000) is given, followed by K lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to N). All the numbers in a line are separated by a space.

Output Specification:

For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.

Sample Input:

3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3

Sample Output:

50.0%
33.3%

题目描述:求两个集合中,相同元素在两个集合中占比为多少。

输入数据:给n组集合,每组集合有m个元素,题目给出k组查询,每组询问两集合中相同元素的占比。

分析输入样例

查询1、2集合:相同数2(87 101)/总数4(87 101 99 87 5)=0.5
查询1、3集合:相同数2(99 101)/总数6(99 87 101 18 5 135)=0.3

注意最后一个测试点容易超时,使用set的find()。


#include<bits/stdc++.h>
using namespace std;
vector< set<int> > v;
int main()
{
	int n, m, k, g;
	scanf("%d", &n);
	v.resize(n+1);
	for(int i=1; i<=n; i++){
		scanf("%d", &m);
		for(int j=0; j<m; j++){
			scanf("%d", &g);
			v[i].insert(g);
		}
	}
	int count=0, all_num=0, a, b;
	scanf("%d", &k);
	set<int>::iterator it;
	for(int i=0; i<k; i++){
		scanf("%d %d", &a, &b);
		all_num = v[a].size()+v[b].size();
		count = 0;
		for(it=v[a].begin(); it!=v[a].end(); it++){
			if(v[b].find(*it)!=v[b].end()) count++;//在集合b中可以找到 
		}
		printf("%.1f%\n", count*100.0/(all_num-count));//共同的元素出现了两次 
	}
	return 0;
}