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;
#define rep(n) for (int i = 0; i < n; ++i)
#define rep2(n) for (int j = 0; j < n; ++j)
#define mp make_pair
#define pb push_back
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
const int maxn = 2e5;
int loves[maxn];
bool been[maxn] = {};
int dfs (int i) {
been[i] = 1;
return 1+(been[loves[i]]?0:(loves[i]));
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
map<string, int> decode;
int n, num = 1, loved[maxn], ans = 0;
string s, t;
cin >> n;
if (n%2==1) {
cout << "-1\n";
return 0;
}
rep (n) {
cin >> s >> t;
if (!decode[s]) decode[s] = num++;
if (!decode[t]) decode[t] = num++;
loves[decode[s]] = decode[t];
loved[decode[t]]++;
}
queue<int> q;
for (int i = 1; i <= n; ++i) {
if (i==loves[loves[i]] && loves[i]!=i) {
been[i] = 1;
been[loves[i]] = 1;
}
else if (loved[i]==0) q.push(i);
}
while (!q.empty()) {
int id = q.front();
q.pop();
been[id] = 1;
if (!been[loves[id]]) {
been[loves[id]] = 1;
if (--loved[loves[loves[id]]]==0) q.push(loves[loves[id]]);
}
ans++;
}
for (int i = 1; i <= n; ++i) {
if (!been[i]) ans += (dfs(i)+1)/2;
}
cout << ans << "\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... |