#include <bits/stdc++.h>
// author: aykhn
using namespace std;
#define int long long
#define inf 0x3F3F3F3F
const int MXN = 1e5 + 5;
int n;
vector<int> adj[MXN];
map<string, int> mp;
int to[MXN], dp[MXN][2];
void dfs(int a)
{
dp[a][0] = dp[a][1] = inf;
if (adj[a].empty())
{
dp[a][0] = 1;
dp[a][1] = inf;
return;
}
dp[a][0] = 0;
for (int v : adj[a])
{
dfs(v);
dp[a][0] += min(dp[v][0], dp[v][1]);
}
for (int v : adj[a])
{
dp[a][1] = min(dp[a][1], dp[a][0] - min(dp[v][0], dp[v][1]) + dp[v][0] - 1);
}
dp[a][0]++;
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(nullptr);
int n, m = 0;
cin >> n;
if (n & 1)
{
cout << -1 << '\n';
return 0;
}
for (int i = 1; i <= n; i++)
{
string a, b;
cin >> a >> b;
if (mp.find(a) == mp.end()) mp[a] = ++m;
if (mp.find(b) == mp.end()) mp[b] = ++m;
to[mp[a]] = mp[b];
}
vector<int> r;
for (int i = 1; i <= m; i++)
{
if (to[i] == i) r.push_back(i);
if (to[to[i]] == i) continue;
adj[to[i]].push_back(i);
}
int res = 0;
for (int i : r)
{
dfs(i);
res += min(dp[i][0], dp[i][1]);
}
cout << (n + res)/2 << '\n';
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
4956 KB |
Output is correct |
2 |
Correct |
1 ms |
4956 KB |
Output is correct |
3 |
Correct |
1 ms |
4956 KB |
Output is correct |
4 |
Correct |
1 ms |
4904 KB |
Output is correct |
5 |
Correct |
1 ms |
2908 KB |
Output is correct |
6 |
Correct |
1 ms |
2908 KB |
Output is correct |
7 |
Incorrect |
1 ms |
5208 KB |
Output isn't correct |
8 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
4956 KB |
Output is correct |
2 |
Incorrect |
1 ms |
4956 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
159 ms |
15660 KB |
Output is correct |
2 |
Correct |
145 ms |
17344 KB |
Output is correct |
3 |
Correct |
139 ms |
13940 KB |
Output is correct |
4 |
Correct |
1 ms |
2908 KB |
Output is correct |
5 |
Correct |
155 ms |
23284 KB |
Output is correct |
6 |
Correct |
138 ms |
14764 KB |
Output is correct |
7 |
Correct |
137 ms |
14604 KB |
Output is correct |
8 |
Correct |
127 ms |
14432 KB |
Output is correct |
9 |
Correct |
130 ms |
14356 KB |
Output is correct |
10 |
Correct |
101 ms |
13780 KB |
Output is correct |
11 |
Correct |
1 ms |
4952 KB |
Output is correct |
12 |
Correct |
2 ms |
4956 KB |
Output is correct |
13 |
Correct |
2 ms |
4956 KB |
Output is correct |
14 |
Correct |
1 ms |
4956 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
4956 KB |
Output is correct |
2 |
Correct |
1 ms |
4956 KB |
Output is correct |
3 |
Correct |
1 ms |
4956 KB |
Output is correct |
4 |
Correct |
1 ms |
4904 KB |
Output is correct |
5 |
Correct |
1 ms |
2908 KB |
Output is correct |
6 |
Correct |
1 ms |
2908 KB |
Output is correct |
7 |
Incorrect |
1 ms |
5208 KB |
Output isn't correct |
8 |
Halted |
0 ms |
0 KB |
- |