CF1503D 题解
Solution
竞选最长做法
假设我们已经翻转好了
令
观察答案形式。发现开头是一段
发现对于左右段交界处的
此时有了一个
发现这个暴力复杂度太高无法承受。考虑优化。发现如果能染色,则方案唯二(钦定第一个点为黑还是白)。注意到我们不需要
易得对每个连通块维护
时间复杂度来到了惊人的
Code
#define _pair array<int, 2>
#define pb push_back
#define For(i, l, r) for (int i = (l); i <= (r); ++i)
#define Rep(i, r, l) for (int i = (r); i >= (l); --i)
#define N 200400
struct _data {
int a, b;
} a[N];
int T[N * 2], tw[N * 2], vis[N * 2], w[N * 2], c[N];
vector<int> g[N];
void add(int u, int v) {
g[u].pb(v); g[v].pb(u);
}
int les(int x) {
return min(a[x].a, a[x].b);
}
struct cmp {
bool operator()(const int x, const int y) {
return les(x) < les(y);
}
};
priority_queue<int, vector<int>, cmp> pq[N];
struct Qcmp {
bool operator()(const int x, const int y) {
return cmp()(pq[x].top(), pq[y].top());
}
};
priority_queue<int, vector<int>, Qcmp> Q;
int fa[N];
int find(int x) {
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void merge(int x, int y) {
int fx = find(x), fy = find(y);
if (pq[fx].size() < pq[fy].size()) swap(x, y), swap(fx, fy);
fa[fy] = fx;
while (!pq[fy].empty()) {
pq[fx].push(pq[fy].top()); pq[fy].pop();
}
}
_pair dfs(int u, int fa, int col) {
vis[u] = 1; c[u] = col;
_pair ans{1, col != w[u]};
for (auto&v : g[u]) if (v != fa) {
auto d = dfs(v, u, 1 - col);
ans[0] += d[0], ans[1] += d[1];
}
return ans;
}
void solve() {
int n; cin >> n;
For (i, 1, n) {
cin >> a[i].a >> a[i].b;
if (max(a[i].a, a[i].b) <= n || les(i) > n) {
cout << "-1"; return;
}
T[a[i].a] = T[a[i].b] = i;
tw[a[i].a] = a[i].b; tw[a[i].b] = a[i].a;
w[i] = (a[i].a > a[i].b);
}
For (i, 1, n) fa[i] = i, pq[i].push(i);
Rep (j, 2 * n, n + 1) {
int i = T[j];
while (!Q.empty() && les(pq[Q.top()].top()) > tw[j]) {
auto u = Q.top(); Q.pop();
add(pq[u].top(), i); merge(u, i);
}
Q.push(find(i));
}
int ans = 0;
For (i, 1, n) if (!vis[i]) {
auto k = dfs(i, 0, 0);
ans += min(k[1], k[0] - k[1]);
}
For (i, 1, n) if (c[i] != (a[i].a > a[i].b)) swap(a[i].a, a[i].b);
sort(a + 1, a + n + 1, [](auto x, auto y) {
return x.a < y.a;
});
For (i, 2, n) if (a[i].b > a[i - 1].b) {
cout << "-1"; return;
}
cout << ans;
}