《Problem A: 求集合的交并补集》
Time Limit: 1 Sec Memory Limit: 4 MBSubmit: 973 Solved: 242
[Submit][Status][Web Board]
Description
任意给定两个包含1-30000个元素的集合A,B(集合中元素类型为任意整型数,且严格递增排列),求A交B、A并B、A-B和B-A集合。
Input
输入第一行为测试数据组数。每组测试数据两行,分别为集合A、B。每行第一个数n(1<=n<=30000)为元素数量,后面有n个严格递增的绝对值小于2^31代表集合中包含的数。
Output
对每组测试数据输出5行,第1行为数据组数,后4行分别为按升序输出两个集合的A交B、A并B、A-B和B-A集合。格式见样例。
Sample Input
1
3 1 2 5
4 2 3 5 8
Sample Output
Case #1:
2 5
1 2 3 5 8
1
3 8
法1:
<span style="font-size:18px;">#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
void put_in(set<int> &p){
int q;
cin>>q;
while(q --){
int value;
cin>>value;
p.insert(value);
}
}
void put_out(set<int> &p){
set<int>::iterator it = p.begin();
while(it != p.end()){
cout<<*it<<" ";
it ++;
}
}
int main(){
int T,T1=1;
cin>>T,T1;
while(T1 <= T){
set<int> A,B,RUnion,RIntersec,RDiff1,RDiff2;
put_in(A);
put_in(B);
set_intersection(A.begin(),A.end(),B.begin(),B.end(),inserter(RIntersec,RIntersec.begin()));
set_union(A.begin(),A.end(),B.begin(),B.end(),inserter(RUnion,RUnion.begin()));
set_difference(A.begin(),A.end(),B.begin(),B.end(),inserter(RDiff1,RDiff1.begin()));
set_difference(B.begin(),B.end(),A.begin(),A.end(),inserter(RDiff2,RDiff2.begin()));
cout<<"Case #"<<T1 ++<<":"<<endl;
put_out(RIntersec); cout<<endl;
put_out(RUnion); cout<<endl;
put_out(RDiff1); cout<<endl;
put_out(RDiff2);cout<<endl;
}
return 0;
}</span>
法2:
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
void put_in(set<int> &p){
int q;
cin>>q;
while(q --){
int value;
cin>>value;
p.insert(value);
}
}
void put_out(set<int> &p){
set<int>::iterator it = p.begin();
while(it != p.end()){
cout<<*it<<" ";
it ++;
}
}
void Intersection(set<int> &A,set<int> &B,set<int> &result){
set<int>::iterator it;
it = A.begin();
while(it != A.end()){
if(B.find(*it) != B.end()) result.insert(*it);
it++;
}
}
void Union(set<int> &A,set<int> &B,set<int> &result){
set<int>::iterator it;
it = A.begin();
while(it != A.end()){
result.insert(*it);
it++;
}
it = B.begin();
while(it != B.end()){
result.insert(*it);
it++;
}
}
void Difference(set<int> &A,set<int> &B,set<int> &result){
set<int>::iterator it;
it = A.begin();
while(it != A.end()){
if(B.find(*it) == B.end()) result.insert(*it);
it++;
}
}
int main(){
int T,T1=1;
cin>>T,T1;
while(T1 <= T){
set<int> A,B,RUnion,RIntersec,RDiff1,RDiff2;
put_in(A);
put_in(B);
Intersection(A,B,RIntersec);
Union(A,B,RUnion);
Difference(A,B,RDiff1);
Difference(B,A,RDiff2);
cout<<"Case #"<<T1 ++<<":"<<endl;
put_out(RIntersec); cout<<endl;
put_out(RUnion); cout<<endl;
put_out(RDiff1); cout<<endl;
put_out(RDiff2); cout<<endl;
}
return 0;
}