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 MAX_N = 1e5;
int n;
bool vis[MAX_N + 1], isOnCycle[MAX_N + 1];
int repr[MAX_N + 1], parent[MAX_N + 1], sizee[MAX_N + 1], dp[MAX_N + 1][2];
vector <int> adj[MAX_N + 1];
unordered_map <string, int> nameToId;
void findCycles( int u, int r ) {
repr[u] = r;
for ( int v: adj[u] ) {
if ( repr[v] == r ) {
isOnCycle[u] = true;
return;
}
if ( repr[v] == 0 )
findCycles( v, r );
if ( isOnCycle[v] ) {
isOnCycle[u] = true;
return;
}
}
}
void detectCycles() {
for ( int v = 1; v <= n; v++ )
vis[v] = false;
for ( int v = 1; v <= n; v++ ) {
if ( vis[v] )
continue;
findCycles( v, v );
}
}
void calc( int u ) {
sizee[u] = 1;
for ( int v: adj[u] ) {
if ( isOnCycle[v] )
continue;
calc( v );
dp[u][false] += dp[v][true];
sizee[u] += sizee[v];
}
dp[u][true] = dp[u][false] + 1;
for ( int v: adj[u] ) {
if ( isOnCycle[v] )
continue;
dp[u][true] = min( dp[u][true], dp[u][false] - dp[v][true] + dp[v][false] + 1 );
}
}
int main() {
cin >> n;
int id = 0;
for ( int i = 0; i < n; i++ ) {
string s, t;
cin >> s >> t;
nameToId[s] = (nameToId[s] == 0 ? ++id : nameToId[s]);
nameToId[t] = (nameToId[t] == 0 ? ++id : nameToId[t]);
parent[nameToId[s]] = nameToId[t];
adj[nameToId[t]].push_back( nameToId[s] );
//cout << nameToId[s] << " " << nameToId[t] << "\n";
}
if ( n % 2 == 1 ) {
cout << -1 << "\n";
return 0;
}
detectCycles();
for ( int u = 1; u <= n; u++ ) {
if ( !isOnCycle[u] )
continue;
calc( u );
}
int ans = 0;
for ( int v = 1; v <= n; v++ ) {
if ( !isOnCycle[v] )
continue;
vector <int> cycle;
int u = v;
do {
cycle.push_back( u );
u = parent[u];
} while ( u != v );
if ( cycle.size() == 1 ) {
ans += dp[cycle[0]][true];
continue;
}
if ( cycle.size() == 2 ) {
ans += dp[cycle[0]][false] + dp[cycle[1]][false];
continue;
}
exit( 1 );
}
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... |