Submission #987810

#TimeUsernameProblemLanguageResultExecution timeMemory
987810MilosMilutinovicLove Polygon (BOI18_polygon)C++14
100 / 100
281 ms34248 KiB
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> to(n); map<string, int> mp; for (int i = 0; i < n; i++) { string s; cin >> s; string t; cin >> t; if (!mp.count(s)) { mp[s] = (int) mp.size(); } if (!mp.count(t)) { mp[t] = (int) mp.size(); } to[mp[s]] = mp[t]; } if (n % 2 == 1) { cout << -1 << '\n'; return 0; } vector<vector<int>> ch(n); for (int i = 0; i < n; i++) { if (to[i] == i) { continue; } ch[to[i]].push_back(i); } vector<int> deg(n); for (int i = 0; i < n; i++) { deg[to[i]] += 1; } vector<int> que; for (int i = 0; i < n; i++) { if (deg[i] == 0) { que.push_back(i); } } for (int b = 0; b < (int) que.size(); b++) { int i = que[b]; deg[to[i]] -= 1; if (deg[to[i]] == 0) { que.push_back(to[i]); } } vector<vector<int>> dp(n, vector<int>(2)); vector<int> comp; function<void(int, int)> Solve = [&](int v, int ban) { comp.push_back(v); int mx = 0; for (int u : ch[v]) { Solve(u, ban); dp[v][0] += max(dp[u][0], dp[u][1]); dp[v][1] += max(dp[u][0], dp[u][1]); if (u != ban) { mx = max(mx, -max(dp[u][0], dp[u][1]) + dp[u][0] + 1); } } dp[v][1] += mx; if (v == ban) { dp[v][1] = 0; } }; int res = 0; for (int i = 0; i < n; i++) { if (deg[i] == 0) { continue; } if (to[i] == i) { Solve(i, -1); res += max(dp[i][1], dp[i][0]); } else if (i == to[to[i]]) { deg[i] = 0; deg[to[i]] = 0; { vector<int> new_ch; for (int x : ch[i]) { if (x == to[i]) { continue; } new_ch.push_back(x); } ch[i] = new_ch; } { vector<int> new_ch; for (int x : ch[to[i]]) { if (x == i) { continue; } new_ch.push_back(x); } ch[to[i]] = new_ch; } Solve(i, -1); Solve(to[i], -1); res += max(max(dp[i][0], dp[i][1]) + max(dp[to[i]][0], dp[to[i]][1]), dp[i][0] + dp[to[i]][0] + 2); } else { vector<int> new_ch; for (int x : ch[to[i]]) { if (x == i) { continue; } new_ch.push_back(x); } ch[to[i]] = new_ch; int prv = to[i]; to[i] = i; comp.clear(); Solve(i, -1); int c = max(dp[i][0], dp[i][1]); for (int x : comp) { dp[x][0] = 0; dp[x][1] = 0; deg[x] = 0; } Solve(i, prv); c = max(c, dp[i][0] + 1); res += c; } } cout << (n - 2 * res) + res << '\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...