Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 1063. Set Similarity

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%

解答

#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;

set<int> v[51];
vector<int> rs;
int a[51][51], b[51][51]; //交集、并集大小

int main()
{
	int n; scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		int m, t; scanf("%d", &m); 
		while (m--)	scanf("%d", &t),v[i].insert(t);
	}

	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
		{
			rs.resize(v[i].size() + v[j].size());
			auto p = set_intersection(v[i].begin(), v[i].end(), v[j].begin(), v[j].end(), rs.begin());
			a[i][j] = p - rs.begin();

			p = set_union(v[i].begin(), v[i].end(), v[j].begin(), v[j].end(), rs.begin());
			b[i][j] = p - rs.begin();
		}

	int q; scanf("%d", &q);
	while (q--)
	{
		int x, y; scanf("%d%d", &x, &y); x--, y--;
		printf("%.1lf%%\n", double(a[x][y]) / b[x][y] * 100);
	}
	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论