a836簡單交集大小決定集合關係
CPE:Simply Subsets (UVa 496)
按相等、真包含、互斥與交疊分類。
解題思路
令 c=|A∩B|。若 c 同時等於 |A|、|B|,兩集合相等;若只等於 |A|,A 是 B 的真子集;若只等於 |B|,則 B 是 A 的真子集。這些檢查應放在 c=0 的互斥判斷之前,才能正確處理空集合。
剩下若 c=0 就互不相交,否則有交集卻互不包含,輸出 I'm confused!。輸入每兩行構成一筆,行界線本身有意義,不能把全檔 split 後失去兩個集合的分界。用 set 表示集合並計算交集,不需比對原始排列順序。
兩種語言都先規範化十進位字串:移除正號與前導零,-0、+000 等都成為 0,非零負數才保留負號。這使數值相等當且僅當字串相等。C++ 的 set<string> 雖按字典序排列,這題只用成員查找、相等與交集,無需數值排序,因此字典序完全足夠。Python 同樣以字串為集合鍵,不用 int() 解析長數值,也不更改十進位轉換安全設定。
Step-by-step animation
示意:A={1,2},B={2,3}
步驟 1 / 3
讀集合
兩集合各有兩個不同元素。
A:1,2
B:2,3
- |A|
- 2
- |B|
- 2
#include <iostream>
#include <string>
#include <sstream>
#include <set>
using namespace std;
string normalizeDecimal(const string &s) {
size_t first = 0;
bool negative = false;
if (!s.empty() && (s[0] == '+' || s[0] == '-')) {
negative = s[0] == '-';
first = 1;
}
while (first < s.size() && s[first] == '0')
++first;
if (first == s.size())
return "0";
string digits = s.substr(first);
return negative ? "-" + digits : digits;
}
set<string> parse(const string &s) {
istringstream in(s);
set<string> result;
string x;
while (in >> x)
result.insert(normalizeDecimal(x));
return result;
}
int main() {
string first, second;
while (getline(cin, first) && getline(cin, second)) {
auto a = parse(first), b = parse(second);
size_t common = 0;
for (const string &x : a)
common += b.count(x);
if (common == a.size() && common == b.size())
cout << "A equals B\n";
else if (common == a.size())
cout << "A is a proper subset of B\n";
else if (common == b.size())
cout << "B is a proper subset of A\n";
else if (!common)
cout << "A and B are disjoint\n";
else
cout << "I'm confused!\n";
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。