![[Swust OJ 632]--集合运算(set容器) [Swust OJ 632]--集合运算(set容器)](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700)
题目链接: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}
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的元素
第一行输入集合A的元素个数M1(M1>=0),接下来一行输入集合A的元素
第三行输入集合B的元素个数M2(M2>=0),最后一行输入集合B的元素
Output
输出共7行
前2行分别输出集合A、B,接下5行来分别输出集合A、B的并(A∪B)、交(A∩B)、差(A – B)、补。
前2行分别输出集合A、B,接下5行来分别输出集合A、B的并(A∪B)、交(A∩B)、差(A – B)、补。
Sample Input
4
1 3 2 1
|
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~~~
#include <iostream>
#include <set>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std; set<int>a, b, c, d, e, f, g;
int n, m, x; void init(){
a.clear(); b.clear();
c.clear(); d.clear();
e.clear(); f.clear(); g.clear();
} void Order(string str, set<int>s){
cout << str << "={";
for (set<int>::iterator it = s.begin(); it != s.end(); it++){
if (it == s.begin()) cout << *it;
else cout << ", " << *it;
}
cout << "}" << endl;
}
int main(){
while (cin >> n){
init();
for (int i = ; i < n; i++){
cin >> x;
a.insert(x);
}
cin >> m;
for (int i = ; i < m; i++){
cin >> x;
b.insert(x);
}
set_union(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(c, c.begin()));//并
set_intersection(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(d, d.begin()));//交
set_difference(a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(e, e.begin()));//差
set_difference(c.begin(), c.end(), a.begin(), a.end(), insert_iterator<set<int> >(f, f.begin()));
set_difference(c.begin(), c.end(), b.begin(), b.end(), insert_iterator<set<int> >(g, g.begin()));
Order("A", a);
Order("B", b);
Order("AuB", c);
Order("AnB", d);
Order("A-B", e);
Order("SA", f);
Order("SB", g);
}
return ;
}