| # | Time | Username | Problem | Language | Result | Execution time | Memory |
|---|---|---|---|---|---|---|---|
| 1333728 | Hduong | Love Polygon (BOI18_polygon) | C++20 | 27 ms | 11036 KiB |
#include <bits/stdc++.h>
#define task "task"
using namespace std;
const int N = 200005;
const int HASH_SIZE = 199999;
long long n, love[N], in_degree[N];
bool matched[N];
struct node {
string key;
long long val;
node* next;
};
node* head[HASH_SIZE];
long long cnt = 1;
long long get_id(string s) {
unsigned long long h = 0;
for (char c : s) h = h * 31 + c;
int idx = h % HASH_SIZE;
node* curr = head[idx];
while (curr != nullptr) {
if (curr->key == s) return curr->val;
curr = curr->next;
}
node* newnode = new node();
newnode->key = s;
newnode->val = cnt++;
newnode->next = head[idx];
head[idx] = newnode;
return newnode->val;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
if (fopen(task".inp", "r")) {
freopen(task".inp", "r", stdin);
freopen(task".out", "w", stdout);
}
cin >> n;
if (n % 2 != 0) {
cout << -1;
return 0;
}
for (int i = 1; i <= n; i++) {
string u_s, v_s;
cin >> u_s >> v_s;
long long u = get_id(u_s), v = get_id(v_s);
love[u] = v;
in_degree[v]++;
}
long long res = 0;
for (int i = 1; i <= n; i++) {
if (!matched[i]) {
int j = love[i];
if (i != j && love[j] == i && !matched[j]) {
matched[i] = true;
matched[j] = true;
}
}
}
queue<long long> q;
for (int i = 1; i <= n; i++) {
if (in_degree[i] == 0) q.push(i);
}
while (!q.empty()) {
long long u = q.front();
q.pop();
if (matched[u]) continue;
long long v = love[u];
if (!matched[v]) {
matched[u] = true;
matched[v] = true;
res += 1;
}
in_degree[v]--;
if (in_degree[v] == 0) q.push(v);
}
for (int i = 1; i <= n; i++) {
if (!matched[i]) {
long long curr = i, siz = 0;
vector<long long> nodes;
while (!matched[curr]) {
matched[curr] = true;
nodes.push_back(curr);
curr = love[curr];
siz++;
}
if (siz >= 2 && love[nodes.back()] == nodes[0]) {
res += (siz / 2);
if (siz % 2 != 0) {
matched[nodes.back()] = false;
}
} else {
for (int k = 0; k < nodes.size(); k++) {
matched[nodes[k]] = false;
}
}
}
}
long long tmp = 0;
for (int i = 1; i <= n; i++) {
if (!matched[i]) tmp++;
}
res += tmp;
cout << res;
}
Compilation message (stderr)
| # | 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... | ||||
