This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
template <class T>
using Vec = std::vector<T>;
int main() {
int N;
std::cin >> N;
if (N % 2 == 1) {
std::cout << -1 << '\n';
return 0;
}
Vec<int> to(N);
{
Vec<std::string> U(N), V(N);
for (int i = 0; i < N; ++i) {
std::cin >> U[i] >> V[i];
}
auto cmp = U;
std::sort(cmp.begin(), cmp.end());
for (int i = 0; i < N; ++i) {
const int u = std::lower_bound(cmp.cbegin(), cmp.cend(), U[i]) - cmp.cbegin();
const int v = std::lower_bound(cmp.cbegin(), cmp.cend(), V[i]) - cmp.cbegin();
to[u] = v;
}
}
Vec<int> deg(N);
for (int i = 0; i < N; ++i) {
deg[to[i]] += 1;
}
Vec<Vec<int>> tree(N);
Vec<bool> used(N);
{
std::queue<int> que;
for (int i = 0; i < N; ++i) {
if (deg[i] == 0) {
que.push(i);
}
}
while (!que.empty()) {
const auto u = que.front();
que.pop();
tree[to[u]].push_back(u);
deg[to[u]] -= 1;
if (deg[to[u]] == 0) {
que.push(to[u]);
}
used[u] = true;
}
}
const auto dfs = [&](auto&& dfs, const int u) -> std::array<int, 2> {
std::array<int, 2> ret{};
int max_dif = 0;
for (const auto v: tree[u]) {
const auto [x, y] = dfs(dfs, v);
ret[0] += std::max(x, y);
max_dif = std::max(max_dif, (x + 1) - std::max(x, y));
}
ret[1] = ret[0] + max_dif;
return ret;
};
int use = 0;
for (int src = 0; src < N; ++src) {
if (used[src]) {
continue;
}
Vec<std::array<int, 2>> val;
{
int u = src;
while (!used[u]) {
val.push_back(dfs(dfs, u));
used[u] = true;
u = to[u];
}
}
const int len = (int) val.size();
if (len == 1) {
use += std::max(val[0][0], val[0][1]);
continue;
}
if (len == 2) {
use += val[0][0] + val[1][0] + 2;
continue;
}
std::array<std::array<int, 2>, 2> dp{};
dp[0][0] = val[0][0];
dp[0][1] = val[0][1];
dp[1][1] = val[0][0] + 1;
for (int i = 1; i < len; ++i) {
std::array<std::array<int, 2>, 2> next{};
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
for (int l = 0; l < 2; ++l) {
for (int m = 0; m < 2; ++m) {
if (j + l + m > 1) {
continue;
}
next[m][k] = std::max(next[m][k], dp[j][k] + val[i][l] + m);
}
}
}
}
dp = std::move(next);
}
use += std::max({ dp[0][0], dp[0][1], dp[1][0] });
}
std::cout << N - use << '\n';
return 0;
}
# | 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... |