/*
ID: agageld1
LANG: C++17
TASK:
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 400005
#define ff first
#define ss second
#define pb push_back
#define sz(s) (int)s.size()
#define rep(c, a, b) for(c = a; c <= b; c++)
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll n, t, answer, cnt;
pair<string,string> s[N];
map <string,int> out, vis;
map <string,string> par;
int main () {
ios::sync_with_stdio(0);cin.tie(0);
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> s[i].ff >> s[i].ss;
if(s[i].ff == s[i].ss) continue;
out[s[i].ss]++;
par[s[i].ff] = s[i].ss;
}
queue <string> q;
for(int i = 1; i <= n; i++) {
if(s[i].ff == s[i].ss) continue;
if(!out[s[i].ff]) {
out[s[i].ff] = -1;
q.push(s[i].ff);
}
}
if(n%2) {
cout << "-1\n";
return 0;
}
while(!q.empty()) {
string h = q.front();
q.pop();
if(par.find(par[par[h]]) != par.end())
out[par[par[h]]]--;
if(vis[par[h]]) {
cout << "-1\n";
return 0;
}
cnt++;
vis[h] = vis[par[h]] = 1;
for(int i = 1;i <= n; i++) {
if(vis[s[i].ss] == 0 && !out[s[i].ss]) {
q.push(s[i].ss);
out[s[i].ss] = -1;
}
if(vis[s[i].ff] == 0 && !out[s[i].ff]) {
q.push(s[i].ff);
out[s[i].ff] = -1;
}
}
}
cout << cnt << '\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... |