【題解】ZeroJudge d691: 00496 – Simply Subsets

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=d691
【解題想法】

  • (Line 22~30) 找出集合 A 和 B 的交集元素,置於另一集合 st。同時把這些交集元素從集合 A 和 B 中移除。
#include <iostream>
#include <sstream>
#include <set>
using namespace std;

int main() {
    string s;
    stringstream ss;
    while (getline(cin, s)){
        set <string> A, B, st;
        ss.clear();
        ss.str(s);
        while (ss >> s){
            A.insert(s);
        }
        getline(cin, s);
        ss.clear();
        ss.str(s);
        while (ss >> s){
            B.insert(s);
        }
        for (auto i:A){
            if (B.count(i)) {
                st.insert(i);
                B.erase(i);
            }
        }
        for (auto i: st){
            A.erase(i);
        }
        if (A.empty() && B.empty()){
            cout << "A equals B\n";
        } else if (A.empty()){
            cout << "A is a proper subset of B\n";
        } else if (B.empty()){
            cout << "B is a proper subset of A\n";
        } else {
            if (st.empty()){
                cout << "A and B are disjoint\n";
            } else {
                cout << "I'm confused!\n";
            }
        }
    }
    return 0;
}

Python code (credit: Amy Chou)

while True:
    try:
        A = set(map(int, input().split()))
        B = set(map(int, input().split()))
        
        if A == B:
            print("A equals B")
        elif A.issubset(B):
            print("A is a proper subset of B")
        elif B.issubset(A):
            print("B is a proper subset of A")
        elif A.isdisjoint(B):
            print("A and B are disjoint")
        else:
            print("I'm confused!")
    except:
        break
分享本文 Share with friends