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 mxn = 2e5+5;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
typedef pair<int,int>pii;
typedef pair<int,pii>piii;
#define sf scanf
#define pf printf
#define input freopen("in.txt","r",stdin)
#define output freopen("out.txt","w",stdout)
#define inf 1e18
#define ff first
#define ss second
#define MP make_pair
#define pb push_back
#define all(v) v.begin(), v.end()
#define printcase(cases) printf("Case %d:", cases);
#define Unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define FAST ios_base::sync_with_stdio(0);cout.tie(0)
#define endl printf("\n")
#define __lcm(a, b) ((a*b)/__gcd(a, b))
map<string,int>mark;
int vis[mxn];
int in[mxn];
int dir[mxn];
int main()
{
//input;
//output;
int n;
cin >> n;
int pos = 1;
for(int i = 0; i < n; i++)
{
string a, b;
cin >> a >> b;
if(!mark[a]) mark[a] = pos++;
if(!mark[b]) mark[b] = pos++;
int u = mark[a];
int v = mark[b];
in[v]++;
dir[u] = v;
}
if(n&1)
{
cout << "-1\n";
return 0;
}
int ans = 0;
queue<int>q;
for(int i = 1; i <= n; i++)
{
if(dir[i] != i && i==dir[dir[i]])
{
vis[i] = 1;
vis[dir[i]] = 1;
}
}
for(int i = 1; i <= n; i++) if(in[i]==0 && !vis[i]) q.push(i);
while(!q.empty())
{
int u = q.front();
q.pop();
ans++;
vis[u] = 1;
if(!vis[dir[u]])
{
int v = dir[dir[u]];
in[v]--;
if(!vis[v] && in[v]==0) q.push(v);
vis[dir[u]] = 1;
}
}
for(int i = 1; i <= n; i++)
{
if(!vis[i])
{
int cnt = 1;
vis[i] = 1;
for(int cur = dir[i]; cur != i; cur = dir[cur]) cnt++, vis[cur] = 1;
ans+=(cnt+1)/2;
}
}
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... |