DMOJ · ccc14s2

CCC 2014 S2 Assigning Partners

This C++ solution uses reciprocal partner map for CCC 2014 S2 Assigning Partners. Read the reasoning, inspect the code, or try your own test case below.

ccc14s2CCC 2014 S2Data structuresReciprocal partner mapC++33 lines
Solution248of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Reciprocal partner map

Store each first-list name and its assigned partner. Reject self-pairs immediately, then check that every A → B assignment is matched by B → A.

Hash mapCCC
Time
O(n) expected
Space
O(n)

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

CCC_2014_J5_S2_Assigning_Partners.cpp

C++

    #include <iostream>
    #include <string>
    #include <unordered_map>
    #include <vector>
    using namespace std;
     
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
     
        int n;
        cin >> n;
        vector<string> first(n), second(n);
        for (string& name : first) cin >> name;
        for (string& name : second) cin >> name;
     
        unordered_map<string, string> partner;
        for (int i = 0; i < n; ++i) {
            if (first[i] == second[i]) {
                cout << "bad\n";
                return 0;
            }
            partner[first[i]] = second[i];
        }
     
        for (int i = 0; i < n; ++i) {
            if (partner[second[i]] != first[i]) {
                cout << "bad\n";
                return 0;
            }
        }
        cout << "good\n";
    }
     
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.