TLE 123 是我写假了吗?
查看原帖
TLE 123 是我写假了吗?
249620
Muly楼主2023/11/28 13:22
#include<bits/stdc++.h>
using namespace std;
using Real = long long;
const Real INF = 1e18;
struct Point {
    Real x, y;
    Point() {}
    Point(Real a, Real b) : x(a), y(b) {}
    friend ostream& operator<<(ostream& os, const Point& v) {
        return os << v.x << " " << v.y;
    }
    friend istream& operator>>(istream& is, Point& v) {
        return is >> v.x >> v.y;
    }
    Point& operator+=(const Point& p) {
        x += p.x, y += p.y;
        return *this;
    }
    Point& operator-=(const Point& p) {
        x -= p.x, y -= p.y;
        return *this;
    }
    Point& operator*=(const Real& k) {
        x *= k, y *= k;
        return *this;
    }
    Point operator-() {
        return Point(-x, -y);
    }
    Point operator+(const Point& p) const {
        return Point(*this) += p;
    }
    Point operator-(const Point& p) const {
        return Point(*this) -= p;
    }
    Point operator*(const Real& k) const {
        return Point(*this) *= k;
    }
    bool operator<(const Point& p) const { 
        return x < p.x || (x == p.x && y < p.y);
    }
    Real norm() const {
        return x * x + y * y;
    }
};
using Points = vector<Point>;
Real closest_pair(Points &ps) {
    int n = ps.size();
    if (n == 1) return 0;
    sort(ps.begin(), ps.end());
    auto cmp_y = [&](const Point& p, const Point& q) { return p.y < q.y; };
    vector<Point> cand(n);
    auto dfs = [&](auto self, int l, int r) -> Real {
        if (r - l <= 1) return INF;
        int mid = (l + r) >> 1;
        auto x_mid = ps[mid].x;
        auto res = min(self(self, l, mid), self(self, mid, r));
        inplace_merge(ps.begin() + l, ps.begin() + mid, ps.begin() + r, cmp_y);
        for (int i = l, cur = 0; i < r; i++) {
            if ((ps[i].x - x_mid) * (ps[i].x - x_mid) >= res) continue;
            for (int j = cur - 1; j >= 0; j--) {
                Point diff = {ps[i].x - cand[j].x, ps[i].y - cand[j].y};
                if (diff.y >= res) break;
                res = min(res, diff.norm());
            }
            cand[cur++] = ps[i];
        }
        return res;
    };
    return dfs(dfs, 0, n);
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    Points ps(n);
    for(auto &p : ps) {
        cin >> p;
    }
    cout << closest_pair(ps) << '\n';
}
2023/11/28 13:22
加载中...