#include <bits/stdc++.h>
#define sz(a) (int)a.size()
#define all(a) a.begin(), a.end()
using namespace std;
vector<int> a;
vector<int> req;
vector<int> deg;
int n; 
vector<int> neigh;
vector<int> visited;
queue<int> leefs;
int rst=0;
int dfs(int x){
    visited[x]=true;
    if(visited[neigh[x]]||x==neigh[x]) {
        return 1;
    }
    return dfs(neigh[x])+1;
}
signed main() {
    ios_base::sync_with_stdio(false); cin.tie(nullptr);
    cin >> n;
    neigh.resize(n);
    deg.resize(n);
    visited.resize(n);
    map<string,int> mp;
    int t=0;
    for (int i = 0; i < n; i++)
    {
        string sa; string b; cin >> sa >> b;
        if(mp.find(sa)==mp.end()){
             //cerr << sa << " " << t<< "\n";
             mp[sa]=t++;
        }
        if(mp.find(b)==mp.end()) {
            //cerr << b << " " << t <<"\n";
            mp[b]=t++;
        }
        neigh[mp[sa]]=mp[b];
        deg[mp[b]]++;
    }
    for (int i = 0; i < n; i++){
        if(neigh[i]!=i&&neigh[neigh[i]]==i){
            visited[neigh[i]]=true;
            visited[i]=true;
        }
    }  
    
    for (int i = 0; i < n; i++)  
    {
        if(visited[i]) continue;
        rst+=(dfs(i)+1)/2;
    }
    if(n%2) cout << -1 << "\n";
    else cout << rst << "\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... |