This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    if (n%2)
    {
        cout << "-1" << endl;
        return 0; 
    }
    map<string, int> m;
    vector<int> il(n, -1), lm(n, 0), happy(n, 0); // koho ja lubim, kolko postav lubi mna?
    int cnt = 0;
    for (int i = 0; i < n; i++)
    {
        string a, b;
        cin >> a >> b;
        if (!m.count(a)) m[a] = cnt++;
        if (!m.count(b)) m[b] = cnt++;
        int ia = m[a], ib = m[b];
        il[ia] = ib, lm[ib]++;
        if (ia != ib && il[ib] == ia) happy[ia] = happy[ib] = true;
    }
    vector<int> stk;
    for (int i = 0; i < n; i++)
        if (lm[i] == 0) stk.push_back(i);
    int ans = 0, alone = 0;
    while (!stk.empty())
    {
        int i = stk.back(); stk.pop_back();
        if (happy[il[i]])
        {
            alone++;
            happy[i] = true;
            continue;
        }
        happy[i] = happy[il[i]] = true;
        ans++;
        if (!happy[il[il[i]]])
        {
            lm[il[il[i]]]--;
            if (!lm[il[il[i]]]) stk.push_back(il[il[i]]);
        }
    }
    for (int i = 0; i < n; i++)
    {
        if (happy[i]) continue;
        int j = il[i], len = 1;
        happy[i] = true;
        while (j != i)
        {
            happy[j] = true;
            len++;
            j = il[j];
        }
        ans += (len>>1), alone += (len&1);
    }
    cout << ans+alone << "\n";
    return 0;
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |