PAT练习(3)-1021 Set Similarity

来源:互联网 发布:linux jdk 降级 编辑:程序博客网 时间:2024/06/10 01:52

题目地址:牛客网(https://www.nowcoder.com/pat/5/problem/4114): 1021 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.

输入例子:

33 99 87 1014 87 101 5 877 99 101 18 5 135 18 9921 21 3

输出例子:

50.0%33.3%
思路:

题目要求两个集合中相同数字的个数和总的个数。在输入的时候可能有重复的数字,需要去除;在求相同数字个数的时候,关键是避免时间复杂度过大,比如遍历一个集合,再去第二个集合中寻找其相同数字,复杂度就是O(n)了,测试中发现这样超时了。

参考网站上的解题报告(https://www.nowcoder.com/discuss/428),在输入的时候使用set保存数据,可以自动滤去重复数字,并将数字从小到大排序;然后寻找相同数字的时候只需要从两个集合开始遍历,

①如果相同就都往后移动,计数;

②如果集合1当前数字小于集合2当前数字,集合1往后移动,集合2不需要;反之亦然;

③直到其中某一个集合到达终点就可以了。

总的数字=集合1大小+集合2大小-相同数字

答案代码:

#include <iostream>#include <vector>#include <algorithm>#include <map>#include <set>#include <stdio.h>using namespace std;#define N 50#define M 104#define K 2000vector<set<int>> numbers;// float same(int index1, int index2)// {// map<int, int> maps;// set<int>::iterator it;// for (it = numbers[index1].begin();// it != numbers[index1].end();// it++)// {// maps[*it]++;// }// for (it = numbers[index2].begin();// it != numbers[index2].end();// it++)// {// maps[*it]++;// }// int inter = 0;// for (map<int, int>::iterator it = maps.begin();// it != maps.end(); // it++)// {// if (it->second == 2)// inter++;// }// return inter*100.0 / maps.size();// }float same(int index1, int index2){set<int> s1 = numbers[index1];set<int> s2 = numbers[index2];set<int>::iterator it1 = s1.begin();set<int>::iterator it2 = s2.begin();int inter = 0;while (it1 != s1.end() || it2 != s2.end()){if (*it1 == *it2){++inter;if (it1 != s1.end())++it1;if (it2 != s2.end())++it2;}else if (*it1 < *it2){if (it1 != s1.end())++it1;elsebreak;}else if (*it1 > *it2){if (it2 != s2.end())++it2;elsebreak;}}return inter*100.0f / (s1.size() + s2.size() - inter);}int main(){int n, m, k, tmp;cin >> n;for (int index = 0; index < n; ++index){cin >> m;set<int> vectmp;while (m--){cin >> tmp;vectmp.insert(tmp);}numbers.push_back(vectmp);}cin >> k;int index1, index2;for (int i = 0; i < k; i++){cin >> index1 >> index2;printf("%.1f%%\n", same(index1 - 1, index2 - 1));}return 0;}







原创粉丝点击