Submission #696560

#TimeUsernameProblemLanguageResultExecution timeMemory
696560mdbrnowskiLove Polygon (BOI18_polygon)C++17
29 / 100
318 ms20516 KiB
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; int cycle_length(int i, int start, vi& graph, vector<bool>& visited, int length) { visited[i] = true; if (i == start) return length; else return cycle_length(graph[i], start, graph, visited, length+1); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; map<string,int> names; int cur_name = 0; vi graph(n); vector<set<int>> rgraph(n); for (int i = 0; i < n; i++) { string a, b; cin >> a >> b; if (names.find(a) == names.end()) names[a] = cur_name++; if (names.find(b) == names.end()) names[b] = cur_name++; if (names[a] == names[b]) graph[names[a]] = -1; else { graph[names[a]] = names[b]; rgraph[names[b]].insert(names[a]); } } if (n & 1) { cout << -1 << '\n'; return 0; } int res = 0; queue<int> q; for (int i = 0; i < n; i++) if (rgraph[i].size() == 0) q.push(i); do { int u = q.front(); q.pop(); int v = graph[u]; if (v == -1) continue; res++; for (auto x : rgraph[v]) if (x != u) graph[x] = -1; int w = graph[v]; if (w > -1) { rgraph[w].erase(rgraph[w].find(v)); if (rgraph[w].size() == 0) q.push(w); } graph[v] = u; } while (q.size()); vector<bool> visited(n, false); for (int i = 0; i < n; i++) { if (visited[i]) continue; visited[i] = true; if (graph[i] == -1) res++; else { int c = cycle_length(graph[i], i, graph, visited, 1); if (c > 2) res += (c + 1) / 2; } } cout << 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...