题目大意:给你两个集合,判断两个集合的关系(不相交、相等、真子集和其他)。简单判断就可以了,不过STL的set没有交集、并集等操作有点让人觉得不方便...
1 #include <cstdio> 2 #include <iostream> 3 #include <set> 4 using namespace std; 5 6 set<int> intersection(const set<int> &a, const set<int> &b) 7 { 8 set<int>::iterator itA = a.begin(), itB = b.begin(); 9 set<int> c; 10 while (itA != a.end() && itB != b.end()) 11 { 12 if (*itA == *itB) 13 { 14 c.insert(*itA); 15 itA++; 16 itB++; 17 } 18 else if (*itA < *itB) itA++; 19 else if (*itA > *itB) itB++; 20 } 21 return c; 22 } 23 24 int main() 25 { 26 #ifdef LOCAL 27 freopen("in", "r", stdin); 28 #endif 29 int x; 30 while (scanf("%d", &x) != EOF) 31 { 32 set<int> A, B, C; 33 A.insert(x); 34 C.insert(x); 35 while (getchar() != ' ') 36 { 37 scanf("%d", &x); 38 A.insert(x); 39 C.insert(x); 40 } 41 scanf("%d", &x); 42 B.insert(x); 43 C.insert(x); 44 while (getchar() != ' ') 45 { 46 scanf("%d", &x); 47 B.insert(x); 48 C.insert(x); 49 } 50 if (A.size() + B.size() == C.size()) printf("A and B are disjoint "); 51 else if (A == B) printf("A equals B "); 52 else 53 { 54 set<int> s = intersection(A, B); 55 if (A == s) printf("A is a proper subset of B "); 56 else if (B == s) printf("B is a proper subset of A "); 57 else printf("I'm confused! "); 58 } 59 } 60 return 0; 61 }
@2013-11-10 11:50:07
前两天看C++ Primer的时候,看到标准库里有set_union(), set_intersection(), set_difference() 和 set_symmetirc_difference()函数,就重写了一下,提交后和上面那个代码时间一样,不过省了不少功夫哈,对c++还是不熟悉啊,还要多学习。
1 #include <cstdio> 2 #include <iostream> 3 #include <set> 4 #include <algorithm> 5 using namespace std; 6 7 int main() 8 { 9 #ifdef LOCAL 10 freopen("in", "r", stdin); 11 #endif 12 int x; 13 while (scanf("%d", &x) != EOF) 14 { 15 set<int> A, B, C; 16 A.insert(x); 17 C.insert(x); 18 while (getchar() != ' ') 19 { 20 scanf("%d", &x); 21 A.insert(x); 22 C.insert(x); 23 } 24 scanf("%d", &x); 25 B.insert(x); 26 C.insert(x); 27 while (getchar() != ' ') 28 { 29 scanf("%d", &x); 30 B.insert(x); 31 C.insert(x); 32 } 33 if (A.size() + B.size() == C.size()) printf("A and B are disjoint "); 34 else if (A == B) printf("A equals B "); 35 else 36 { 37 set<int> s; 38 set_intersection(A.begin(), A.end(), B.begin(), B.end(), inserter(s, s.begin())); 39 if (A == s) printf("A is a proper subset of B "); 40 else if (B == s) printf("B is a proper subset of A "); 41 else printf("I'm confused! "); 42 } 43 } 44 return 0; 45 }