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;
int main(){
int n, ans = 0; cin >> n;
vector<pair<string,string>> in;
vector<int> belove(n), love(n);
map<string,int> M;
queue<int> nobody;
vector<bool> vis(n,false);
if(n & 1){
cout << "-1\n"; return 0;
}
for(int i = 0; i < n; ++i){
string s1, s2; cin >> s1 >> s2;
M[s1] = i;
in.push_back({s1,s2});
}
for(int i = 0; i < n; ++i){
love[M[in[i].first]] = M[in[i].second];
belove[M[in[i].second]]++;
}
for(int i = 0; i < n; ++i){
if(love[love[i]] == i && love[i] != i)vis[i] = true;
if(!belove[i]){nobody.push(i);}
}
while(!nobody.empty()){
auto x = nobody.front();
nobody.pop();
vis[x] = true;
if(!vis[love[x]]){
vis[love[x]] = true;
if(--belove[love[love[x]]] == 0)nobody.push(love[love[x]]);
}
ans++;
}
for(int i = 0; i < n; ++i){
if(!vis[i]){
vis[i] = true;
int last = i;
vis[last] = true;
int cnt = 1;
while(!vis[love[last]]){
cnt++;
last = love[last];
vis[last] = true;
}
ans+=(cnt+1)>>1;
}
}
cout << ans << "\n";
}
# | 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... |