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>
using namespace std;
const int MAXN = 1e5 + 25;
int p[MAXN], n, deg[MAXN];
map <string, int> d;
bool vis[MAXN];
queue <int> o;
int main () {
ios::sync_with_stdio(0); cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
string s, t;
cin >> s >> t;
if (!d.count(s)) d[s] = (int)d.size();
if (!d.count(t)) d[t] = (int)d.size();
p[d[s]] = d[t];
deg[d[t]]++;
}
if (n & 1) {
cout << "-1\n";
return 0;
}
int ans = 0;
for (int i = 0; i < n; i++) if (deg[i] == 0) o.push(i);
while (!o.empty()) {
auto k = o.front(); o.pop();
if (deg[k] != 0) continue;
if (p[p[k]] != p[k] && p[p[p[k]]] == p[k]) continue;
if (p[p[k]] == p[k]) {
p[p[k]] = k;
deg[k]++; deg[p[k]]--;
ans++;
continue;
}
ans++;
deg[p[p[k]]]--;
if (deg[p[p[k]]] == 0) {
o.push(p[p[k]]);
}
p[p[k]] = k; deg[k]++;
}
for (int i = 0; i < n; i++) {
if (deg[i] == 0) {
ans++;
deg[i] = 2;
deg[p[i]]--;
}
}
for (int i = 0; i < n; i++) {
if (deg[i] == 1 && !vis[i]) {
vector <int> t = {i};
vis[i] = 1;
int u = p[i];
while (u != i) {
t.push_back(u); vis[u] = 1;
u = p[u];
}
if (t.size() == 2) continue;
int z = t.size();
ans += (z >> 1) + (z & 1);
}
}
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... |