[Swust OJ 632]--集合运算(set容器)

题目链接:http://acm.swust.edu.cn/problem/632/

Time limit(ms): 1000      Memory limit(kb): 65535
 
Description
集合的运算就是用给定的集合去指定新的集合。设A和B是集合,则它们的并差交补集分别定义如下: 
A∪B={x|x∈A∨x∈B} 
A∩B={x|x∈A∧x∈B} 
A – B={x|x∈A∧x不属于 B} 
SA ={x|x∈(A∪B)∧x 不属于A} 
SB ={x|x∈(A∪B)∧x 不属于B} 
 
Input
输入可能有2~4行数据 
第一行输入集合A的元素个数M1(M1>=0),接下来一行输入集合A的元素 
第三行输入集合B的元素个数M2(M2>=0),最后一行输入集合B的元素 
 
Output
输出共7行 
前2行分别输出集合A、B,接下5行来分别输出集合A、B的并(A∪B)、交(A∩B)、差(A – B)、补。 
 
Sample Input
4
1 3 2 1
0

Sample Output
A={1, 2, 3}
B={}
AuB={1, 2, 3}
AnB={}
A-B={1, 2, 3}
SA={}
SB={1, 2, 3}

Hint
为了唯一确定输出结果,集合的元素按升序输出
 
解题思路:注意到了升序输出,结合集合运算的特点,直接利用set容器水过Orz~~~
 1 #include <iostream>
 2 #include <set>
 3 #include <string>
 4 #include <algorithm>
 5 #include <iterator>
 6 using namespace std;
 7 
 8 set<int>a, b, c, d, e, f, g;
 9 int n, m, x;
10 
11 void init(){
12     a.clear(); b.clear();
13     c.clear(); d.clear();
14     e.clear(); f.clear(); g.clear();
15 }
16 
17 void Order(string str, set<int>s){
18     cout << str << "={";
19     for (set<int>::iterator it = s.begin(); it != s.end(); it++){
20         if (it == s.begin()) cout << *it;
21         else cout << ", " << *it;
22     }
23     cout << "}" << endl;
24 }
25 int main(){
26     while (cin >> n){
27         init();
28         for (int i = 0; i < n; i++){
29             cin >> x;
30             a.insert(x);
31         }
32         cin >> m;
33         for (int i = 0; i < m; i++){
34             cin >> x;
35             b.insert(x);
36         }
37         set_union(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(c, c.begin()));//
38         set_intersection(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(d, d.begin()));//
39         set_difference(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(e, e.begin()));//
40         set_difference(c.begin(), c.end(), a.begin(), a.end(), insert_iterator<set<int> >(f, f.begin()));
41         set_difference(c.begin(), c.end(), b.begin(), b.end(), insert_iterator<set<int> >(g, g.begin()));
42         Order("A", a);
43         Order("B", b);
44         Order("AuB", c);
45         Order("AnB", d);
46         Order("A-B", e);
47         Order("SA", f);
48         Order("SB", g);
49     }
50     return 0;
51 }
View Code
原文地址:https://www.cnblogs.com/zyxStar/p/4605492.html