2019年9月PAT - 练习笔记——6.2
以下页码标注的是阅读器中实际页码,而不是书本身自印的页码。
第6章 C++标准模板库(STL)介绍
6.2 set的常见用法详解
注意
-
std::set和std::multiset为有序序列,而hash_set以及hash_multiset为无序序列。
-
并交差:https://blog.csdn.net/u013095333/article/details/89322501
- set_union(A.begin(),A.end(),B.begin(),B.end(),inserter( C1 , C1.begin() ) );
- set_intersection(A.begin(),A.end(),B.begin(),B.end(),inserter( C2 , C2.begin() ));
- set_difference( A.begin(), A.end(),B.begin(), B.end(),inserter( C3, C3.begin() ) );
注意!以上函数要求两个集合必须是有序的
目录
- A1063 Set Similarity
-
A1063 Set Similarity
Given two sets of integers, the similarity of the sets is defined to be N**c/N**t×100%, where N**c is the number of distinct common numbers shared by the two sets, and N**t 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 <iostream> #include <vector> #include <set> using namespace std; const int INF = 0x7fffffff; int main(void) { int n = 0; scanf("%d", &n); vector<set<int>> sets(n + 1); for (int i = 1;i <= n;++i) { int m = 0; scanf("%d", &m); for (int j = 0;j < m;++j) { int num = 0; scanf("%d", &num); sets[i].insert(num); } sets[i].insert(INF); } int k = 0; scanf("%d", &k); for (int i = 0;i < k;++i) { int set1 = 0, set2 = 0; scanf("%d %d", &set1, &set2); int count1 = -1, count2 = -1; set<int>::iterator iter1 = sets[set1].begin(), iter2 = sets[set2].begin(); for (;iter1 != sets[set1].end() && iter2 != sets[set2].end();) { int num1 = *iter1, num2 = *iter2; if (num1 == num2) { ++count1; ++iter1; ++iter2; } else if (num1 < num2) ++iter1; else ++iter2; ++count2; } float percent = (float)count1 / count2; printf("%.1f%%\n", percent * 100); } return 0; }
用set_union和set_intersection的话,测试点4会超时
-
《算法笔记》P246
-