Submission #944213

#TimeUsernameProblemLanguageResultExecution timeMemory
944213LucaIlieLove Polygon (BOI18_polygon)C++17
0 / 100
118 ms22840 KiB
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1e5; int n; bool vis[MAX_N + 1], isOnCycle[MAX_N + 1], isUnpaired[MAX_N + 1]; int repr[MAX_N + 1], parent[MAX_N + 1], sizee[MAX_N + 1], dp[MAX_N + 1]; 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 ) { int odd = 0; sizee[u] = 1; for ( int v: adj[u] ) { if ( isOnCycle[v] ) continue; calc( v ); dp[u] += dp[v]; sizee[u] += sizee[v]; if ( sizee[v] % 2 == 1 ) odd++; } dp[u] += odd; } 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(); int ans = 0; for ( int u = 1; u <= n; u++ ) { if ( !isOnCycle[u] ) continue; calc( u ); ans += dp[u]; if ( sizee[u] % 2 == 1 ) isUnpaired[u] = true; } for ( int v = 1; v <= n; v++ ) { if ( parent[v] != v && isUnpaired[v] && isUnpaired[parent[v]] ) { isUnpaired[v] = isUnpaired[parent[v]] = false; if ( parent[parent[v]] != v ) ans++; } } for ( int v = 1; v <= n; v++ ) { if ( isUnpaired[parent[v]] ) ans++; } cout << ans << "\n"; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...