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>
#define pb push_back
#define f first
#define sc second
using namespace std;
typedef long long int ll;
typedef string str;
int n;
vector<vector<int>> v;
vector<int> succ;
vector<bool> bl;
pair<int, int> cycle;
bool cycle_type;
void dfs_cycle(int nd, int ss){
    if(bl[nd]){
        cycle = {ss, nd};
        return;
    }
    bl[nd] = 1;
    unordered_map<int, int> mp;
    for(int x: v[nd]) if(x != ss) dfs_cycle(x, nd), mp[x]++;
    for(auto [x, c]: mp) if(c > 1){
        cycle = {nd, x};
        if(nd != x) cycle_type = 1;
    }
}
int mc = 0;
bool dfs(int nd, int ss, bool type){
    bool s = 0;
    for(int x: v[nd])
        if(x != ss && (nd != cycle.f || x != cycle.sc) && (nd != cycle.sc || x != cycle.f))
            s|=dfs(x, nd, type);
    if(ss == -1 && cycle_type) dfs(cycle.sc, nd, type);
    if(type){
        if(nd == cycle.f) return 0;
        if(nd == cycle.sc){
            mc++;
            return 0;
        }
    }
    if(s) mc++;
    return !s;
}
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n;
    if(n%2 != 0){
        cout << "-1\n";
        exit(0);
    }
    v.assign(n, {});
    succ.assign(n, -1);
    bl.assign(n, 0);
    unordered_map<str, int> mp;
    int in = 0;
    for(int i = 0; i < n; i++){
        str a, b; cin >> a >> b;
        if(mp.find(a) == mp.end()) mp[a] = in, in++;
        if(mp.find(b) == mp.end()) mp[b] = in, in++;  
        succ[mp[a]] = mp[b];
        v[mp[a]].pb(mp[b]);
        v[mp[b]].pb(mp[a]);
    }
    int ans = 0;
    for(int i = 0; i < n; i++){
        if(bl[i]) continue;
        int mx = 0;
        cycle_type = 0;
        dfs_cycle(i, -1);
        mc = 0;
        dfs(cycle.f, -1, 0);
        mx = max(mx, mc);
        if(cycle.f != cycle.sc){
            mc = 0;
            dfs(cycle.f, -1, 1);
            mx = max(mx, mc+cycle_type);
        }
        ans+=mx;
    }
    ans = n-ans;
    cout << ans << "\n";
}
| # | 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... |