#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> to(n);
map<string, int> mp;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
string t;
cin >> t;
if (!mp.count(s)) {
mp[s] = (int) mp.size();
}
if (!mp.count(t)) {
mp[t] = (int) mp.size();
}
to[mp[s]] = mp[t];
}
if (n % 2 == 1) {
cout << -1 << '\n';
return 0;
}
vector<vector<int>> ch(n);
for (int i = 0; i < n; i++) {
if (to[i] == i) {
continue;
}
ch[to[i]].push_back(i);
}
vector<int> deg(n);
for (int i = 0; i < n; i++) {
deg[to[i]] += 1;
}
vector<int> que;
for (int i = 0; i < n; i++) {
if (deg[i] == 0) {
que.push_back(i);
}
}
for (int b = 0; b < (int) que.size(); b++) {
int i = que[b];
deg[to[i]] -= 1;
if (deg[to[i]] == 0) {
que.push_back(to[i]);
}
}
vector<vector<int>> dp(n, vector<int>(2));
function<void(int)> Solve = [&](int v) {
int mx = 0;
for (int u : ch[v]) {
Solve(u);
dp[v][0] += max(dp[u][0], dp[u][1]);
mx = max(mx, -max(dp[u][0], dp[u][1]) + dp[u][0] + 1);
}
dp[v][1] = dp[v][0] + mx;
};
int res = 0;
for (int b = 0; b < (int) que.size(); b++) {
int i = que[b];
Solve(i);
res += dp[i][1];
}
cout << (n - 2 * res) + res << '\n';
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
348 KB |
Output is correct |
2 |
Incorrect |
1 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
248 ms |
21780 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |