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 N = 1e5 + 5;
int n,love[N];
int ind;
unordered_map<string,int>id;
vector <int> g[N],adj[N];
bool mrk[N];
vector<int>ord;
deque<int>dag;
void dfs(int v){
mrk[v]=1;
for (int i=0;i<(int)g[v].size();i++){
int u=g[v][i];
if (!mrk[u]){
adj[v].push_back(u);
dfs(u);
}
}
ord.push_back(v);
return;
}
int used[N];
int max_maching;
bool mark[N];
void maching_dfs(int v, int par){
for(int i=0;i<(int)adj[v].size();i++){
int u=adj[v][i];
maching_dfs(u,v);
}
if(!used[v] && !used[par] && par!=0){
max_maching++;
used[v]=used[par]=1;
}
}
inline int solve1(int root){
max_maching = 0;
for(int i=0;i<(int)ord.size();i++){
int v=ord[i];
used[v]=0;
}
maching_dfs(root,0);
return max_maching;
}
inline int solve2(int root){
if(love[root]==root) return 0;
for(int i=0;i<(int)ord.size();i++){
int v=ord[i];
used[v]=0;
}
used[root]=used[love[root]]=1;
max_maching=0;
maching_dfs(root,0);
return max_maching+1+(int)(love[love[root]]==root);
}
void DFS(int v){
mrk[v]=1;
for(int i=0;i<(int)g[v].size();i++){
int u=g[v][i];
if(mrk[u]) continue;
DFS(u);
}
dag.push_back(v);
return;
}
void fsd(int v){
mrk[v]=1;
for(int i=0;i<(int)g[v].size();i++){
int u=g[v][i];
if(!mrk[u]){
adj[v].push_back(u);
fsd(u);
}
}
ord.push_back(v);
return;
}
int main() {
ios_base::sync_with_stdio(0),cin.tie(0);cout.tie(0);
cin>>n;
if(n%2){
cout<<"-1\n";
return 0;
}
for(int i=1;i<=n;i++){
string a,b;
cin>>a>>b;
if(id.count(a)==0){
id[a]=++ind;
}
if(id.count(b)==0){
id[b]=++ind;
}
int u=id[a];
int v=id[b];
love[u]=v;
g[v].push_back(u);
}
for(int i=1;i<=n;i++){
if(!mrk[i]){
DFS(i);
}
}
for(int i=1;i<=n;i++){mrk[i]=0;}
int ans=n;
while(dag.size()){
int v=dag.back();dag.pop_back();
if(mrk[v])continue;
ord.clear();fsd(v);
ans-=max(solve1(v),solve2(v));
}
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... |