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 int long long
#define ld long double
#define show(x,y) cout << y << " " << #x << endl;
#define show2(x,y,i,j) cout << y << " " << #x << " " << j << " " << #i << endl;
#define show3(x,y,i,j,p,q) cout << y << " " << #x << " " << j << " " << #i << " " << q << " " << #p << endl;
#define show4(x,y) for(auto it:x) cout << it << " "; cout << #y << endl;
typedef pair<int,int>pii;
int pp[100005];
map<string,int>mp;
int ptr=0;
int sz=0;
bool visited[100005];
int in[100005];
void dfs(int index){
sz++;
visited[index]=true;
int nx=pp[index];
if(visited[nx]) return;
dfs(nx);
}
void solve(){
int n;
cin >> n;
string s,s2;
for(int x=0;x<n;x++){
cin >> s >> s2;
if(mp.find(s)==mp.end()){
mp[s]=ptr++;
}
if(mp.find(s2)==mp.end()){
mp[s2]=ptr++;
}
pp[mp[s]]=mp[s2];
//show2(a,mp[s],b,mp[s2]);
in[mp[s2]]++;
}
for(int x=0;x<n;x++){
if(pp[pp[x]]==x&&pp[x]!=x){
//relationship
visited[x]=true;
visited[pp[x]]=true;
}
}
int counter=0;
queue<int>q;
for(int x=0;x<n;x++){
if(in[x]==0) q.push(x);
}
while(!q.empty()){
int cur=q.front();
q.pop();
if(visited[cur]) continue;
int nx=pp[cur];
//show2(cur,cur,nx,nx);
if(visited[nx]){
pp[cur]=cur;
continue;
}
counter++;
in[pp[nx]]--;
if(in[pp[nx]]==0)q.push(pp[nx]);
pp[nx]=cur;
visited[nx]=true;
visited[cur]=true;
}
for(int x=0;x<n;x++){
if(visited[x]) continue;
//show(visit,x);
sz=0;
dfs(x);
if(sz==2) continue;
counter+=(sz+1)/2;
}
if(n%2) cout << -1;
else cout << counter;
}
int32_t main(){
ios::sync_with_stdio(0);
cin.tie(0);
int t=1;
//cin >> t;
while(t--){
solve();
}
}
# | 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... |