如果你會用百度搜一下關鍵字“stl set”,這個題目我相信你會很快很輕松的做出來。加油哦!
set_union
set_intersection
set_difference
我是從這個網站上搜到的,可以借鑒一下!http://blog.chinaunix.net/uid-9950859-id-99130.html
存在一種頭文件#include<bits/stdc++.h>包含了所有C++頭文件。但有些OJ不能使用。
#include<iostream> #include<algorithm> #include<set> using namespace std; void print(const set<int> &t) { set<int>::iterator it; cout << "{"; for(it = t.begin(); it != t.end(); it++) if(it == t.begin()) cout << *it; else cout << ", " << *it; cout << "}" << endl; } int main() { int i,n; cin>>n; for(i=1;i<=n;i++) { cout<<"Case# "<<i<<":"<<endl; int j,m,k; set<int> A; set<int> B; set<int> tmp1,tmp2,tmp3,tmp4,tmp5; cin>>m; for(j=0;j<m;j++) { int t; cin>>t; A.insert(t); } cin>>k; for(j=0;j<k;j++) { int t; cin>>t; B.insert(t); } cout<<"A = "; print(A); cout<<"B = "; print(B); set_union(A.begin(), A.end(), B.begin(), B.end(), inserter(tmp1, tmp1.begin())); cout<<"A u B = "; print(tmp1); set_intersection(A.begin(), A.end(), B.begin(), B.end(), inserter(tmp2, tmp2.begin())); cout<<"A n B = "; print(tmp2); set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(tmp3, tmp3.begin())); cout<<"A - B = "; print(tmp3); set_difference(tmp1.begin(), tmp1.end(), A.begin(), A.end(), inserter(tmp4, tmp4.begin())); cout<<"SA = "; print(tmp4); set_difference(tmp1.begin(), tmp1.end(), B.begin(), B.end(), inserter(tmp5, tmp5.begin())); cout<<"SB = "; print(tmp5); } return 0; }