算法笔记练习 6.2 set 问题 A: 【PAT A1063】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.

输入
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.

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

样例输入

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%

思路

步骤:

  1. sets数组接收n个集合的数据;
  2. 对后续的每一条查询,统计两个集合重复的元素个数same,那么总元素个数即为两个集合的.size()之和减去same,计算结果并输出。

第一次写的时候,查询那边的写法是:把查询的两个集合中的元素全部插入到一个新的集合sum里面,然后通过这总共三个集合的.size()之间的数量关系得出答案,然后超时了。

现在的这一版代码用两个迭代器分别遍历两个集合,明显优化了时间复杂度。

代码

#include 
#include 
using namespace std;

set<int> sets[51];

int main() {
	int n, m, k, input;
	while (scanf("%d", &n) != EOF) {
		for (int i = 1; i != n+1; ++i) {
			scanf("%d", &m);
			while (m--) {
				scanf("%d", &input);
				sets[i].insert(input);
			} 
		}
		scanf("%d", &k);
		while (k--) {
			int a, b, same = 0;
			scanf("%d %d", &a, &b);
			auto ita = sets[a].begin();
			auto itb = sets[b].begin();
			while (ita != sets[a].end() && itb != sets[b].end()) {
				if (*ita == *itb) {
					++same;
					++ita;
					++itb;
				} else if (*ita < *itb) {
					++ita;
				} else {
					++itb;
				} 
			}
			printf("%.1f%%\n", 100.0 * (float)same
				/ (float)(sets[a].size() + sets[b].size() - same));
		} 
	}
	return 0;
} 

你可能感兴趣的:(算法笔记)