제출 #1299082

#제출 시각아이디문제언어결과실행 시간메모리
1299082nguyenkhangninh99Love Polygon (BOI18_polygon)C++20
100 / 100
191 ms23120 KiB
#include<bits/stdc++.h> using namespace std; #define int long long const int maxn = 1e5 + 5; vector<int> rev[maxn]; int par[maxn], deg[maxn], vis[maxn], match[maxn], ans; void dfs(int u){ vis[u] = 1; for(int v: rev[u]){ if(vis[v] || v == u) continue; dfs(v); if(!match[v] && !match[u]){ match[u] = match[v] = 1; ans++; } } } void dfs2(int u){ vis[u] = 1; for(int v: rev[u]){ if(vis[v] || v == u || deg[v] > 0) continue; dfs2(v); if(!match[v] && !match[u]){ match[u] = match[v] = 1; ans++; } } } void dfscycle(int u){ vis[u] = 1; for(int v: rev[u]){ if(deg[v] == 0) continue; if(!vis[v]) dfscycle(v); if(!match[v] && !match[u]){ match[u] = match[v] = 1; ans++; } } } signed main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; if(n & 1){ cout << -1; return 0; } map<string, int> mp; int id = 1; for(int i = 1; i <= n; i++){ string s, t; cin >> s >> t; if(!mp.count(s)) mp[s] = id++; if(!mp.count(t)) mp[t] = id++; int u = mp[s], v = mp[t]; par[u] = v; rev[v].push_back(u); deg[v]++; } queue<int> q; for(int i = 1; i <= n; i++) if(!deg[i]) q.push(i); while(q.size()){ int u = q.front(); q.pop(); int v = par[u]; deg[v]--; if(!deg[v]) q.push(v); } for(int i = 1; i <= n; i++){ if(!deg[i]) continue; if(par[i] > i && par[par[i]] == i){//cycle size 2 match[i] = match[par[i]] = 1; vis[i] = vis[par[i]] = 1; dfs(i); dfs(par[i]); }else if(par[i] != i) dfs2(i);//cycle size > 2 else dfs(i); //cycle size1 } memset(vis, 0, sizeof(vis)); for(int i = 1; i <= n; i++) if(deg[i] && !vis[i] && match[i]) dfscycle(i); for(int i = 1; i <= n; i++) if(deg[i] && !vis[i]) dfscycle(i); for(int i = 1; i <= n; i++) ans += !match[i]; cout << ans; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...