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>
#define eb emplace_back
#define mp make_pair
#define F first
#define S second
#define printv(a, b) { \
for(auto pv : a) b << pv << " "; \
b << "\n"; \
}
using namespace std;
using pii = pair<int, int>;
map<string, int> id;
int num = 1;
int getid(string& s){
if(id.find(s) == id.end()) id[s] = num++;
return id[s];
}
int n;
vector<vector<int>> g;
vector<int> dp0, dp1;
void init(){
g.resize(n + 1);
dp0.resize(n + 1);
dp1.resize(n + 1);
}
void dfs(int now){
int sum = 0, mn = n;
int cnt = 0;
for(int i : g[now]){
if(i == now) continue;
dfs(i);
cnt++;
sum += dp1[i];
mn = min(mn, dp0[i] - dp1[i]);
}
if(cnt == 0){
dp0[now] = 0; dp1[now] = 1;
}
else{
dp0[now] = sum;
dp1[now] = sum + mn + 1;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
init();
vector<int> f(n + 1);
for(int i = 1; i <= n; i++){
string s, t;
cin >> s >> t;
int u = getid(s), v = getid(t);
f[u] = v;
}
for(int i = 1; i <= n; i++){
if(f[f[i]] == i && f[i] != i) continue;
g[f[i]].eb(i);
}
//for(auto& i : id) cerr << i.F << " " << i.S << "\n";
if(n % 2){
cout << "-1\n";
return 0;
}
int ans = 0;
for(int i = 1; i <= n; i++){
if(f[i] != i) continue;
dfs(i);
ans += dp1[i];
}
//printv(dp0, cerr);
//printv(dp1, cerr);
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... |