1 //算法笔记STL部分set篇 2 #include<cstdio> 3 #include<set> 4 const int N = 50; 5 using namespace std; 6 set<int> st[N]; //定义一个集合数组 7 void compare(int x, int y) //输出st[x]与st[y]交集与并集的比率 8 { 9 int difNum = st[x].size(); //1.定义difNum与sameNum,代表两个集合中不同的元素(初始化为x中元素个数)与相同的元素(初始化为0) 10 int sameNum = 0; 11 for(set<int>::iterator it = st[y].begin(); it != st[y].end(); it++) //2.使用迭代器遍历 y集合中的元素 ,使用find()函数在x集合中寻找迭代器所指向的元素,如果相同sameNum++,否则difNum++ 12 { 13 if(st[x].find(*it) == st[x].end()) 14 difNum++; 15 else 16 sameNum++; 17 } 18 printf("%.1lf%%", sameNum * 100.00 / difNum); //3.通过sameNum与difNum计算并输出比率 19 int main() 20 { 21 int n, count, vuale, T, s1, s2; 22 scanf("%d", &n); //n为集合的个数 23 for(int i = 1; i <= n; i++) //为每个集合的元素赋值 24 { 25 scanf("%d", &count); 26 for(int j = 0; j < count; j++) 27 { 28 scanf("%d", &vuale); 29 st[i].insert(vuale); 30 } 31 } 32 scanf("%d", &T); //T为测试的组数 33 for(int i = 0; i < T; i++) //为每组测试选定2个集合 34 { 35 scanf("%d%d", &s1, &s2); 36 compare(s1, s2); 37 } 38 }
原文:https://www.cnblogs.com/the-cat-from-Norway/p/9911267.html