AT_ttpc2023_o 2D Parentheses
AT_ttpc2023_o 2D Parentheses
给定 \(n\) 个左 / 右部点,分别为 \((x_{1,i},y_{1,i})\) 和 \((x_{2,i},y_{2,i})\)。你需要构造一组完美匹配,满足匹配 \((i,j)\) 形成若干 4-side 矩形 \([x_1,x_2] \times [y_1,y_2]\),矩形之间只有包含和相离关系。
输出构造或报告无解。
\(n \le 2\times 10^5\),3 秒,1024 MB。
性质 可能合法的匹配是唯一的。
将左部点按 \(x_i\) 为第一关键字,\(y_i\) 为第二关键字降序排序并扫描。对于每个左下角 \((x_1,y_1)\),取 \(x_1<x_2\) 的最小 \(y_2\) 作为右上角。容易使用 std::set 维护。
由上述过程说明性质,若贪心匹配 \((i,j_1)\),应当匹配 \((i,j_2)\),则 \((i,j_2)\) 与 \((*,j_1)\) 必然有交,从而不合法。

找出匹配后只要实现一个 SPJ,判定矩形是否相交。
对 \(x\) 轴扫描线,转化为插入 / 删除线段,判定线段是否相交。使用 multiset 维护 \(y\) 轴即可,注意将 \(x\) 相同的线段一起处理。
复杂度 \(O(n \log n)\)。
const int N = 2e5 + 5, inf = 1e9;
int n, p[N], ans[N];
struct point {
int x, y, id;
bool operator< (const point& o) const {
if (x == o.x) return y > o.y;
return x > o.x;
}
} a[N], b[N];
set<tuple<int, int, int>> S; // (y2, x2, id)
map<int, vector<tuple<int, int, int>>> P; // (x) -> (y1, y2, op)
void _main() {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i].x >> a[i].y, a[i].id = i;
for (int i = 1; i <= n; i++) cin >> b[i].x >> b[i].y, b[i].id = i;
sort(a + 1, a + n + 1), sort(b + 1, b + n + 1);
for (int i = 1, j = 0; i <= n; i++) {
while (j < n && a[i].x < b[j+1].x)
j++, S.emplace(b[j].y, b[j].x, j);
auto it = S.upper_bound({a[i].y, inf, inf});
if (it == S.end()) return cout << "No", void();
auto [y2, x2, id] = *it;
S.erase(it), p[i] = id;
}
for (int i = 1; i <= n; i++) {
auto [x1, y1, u] = a[i]; auto [x2, y2, v] = b[p[i]];
if (y1 >= y2) return cout << "No", void();
P[x1].pb(y1, y2, +1), P[x2].pb(y1, y2, -1);
ans[u] = v;
}
auto check = [&]() -> bool {
multiset<int> S;
for (auto [x, vec] : P) {
for (auto [y1, y2, op] : vec)
if (op == -1) S.erase(S.find(y1)), S.erase(S.find(y2));
for (auto [y1, y2, op] : vec) {
auto it = S.upper_bound(y1);
if (it != S.end() && *it < y2) return false;
}
for (auto [y1, y2, op] : vec)
if (op == +1) S.emplace(y1), S.emplace(y2);
}
return true;
};
if (!check()) return cout << "No", void();
cout << "Yes\n";
for (int i = 1; i <= n; i++) cout << ans[i] << '\n';
}

浙公网安备 33010602011771号