AcWing 3028. 最小圆覆盖

题链

#include<bits/stdc++.h>//O(n),最小圆覆盖
#define eps 1e-12
using namespace std;

int n,m;
struct node {
    double x, y;
} s[500005];
node o;//圆心坐标
double ri;//半径

double dis(node a, node b) {
    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}

void getr(node p1, node p2, node p3) {//三个点求三角形圆心坐标和半径
    double a, b, c, d, e, f;
    a = p2.y - p1.y;
    b = p3.y - p1.y;
    c = p2.x - p1.x;
    d = p3.x - p1.x;
    f = p3.x * p3.x + p3.y * p3.y - p1.x * p1.x - p1.y * p1.y;
    e = p2.x * p2.x + p2.y * p2.y - p1.x * p1.x - p1.y * p1.y;
    
    o.x = (a * f - b * e) / (2 * a * d - 2 * b * c);
    o.y = (d * e - c * f) / (2 * a * d - 2 * b * c);
    ri = dis(o, p1);
}

int main() {
    ios::sync_with_stdio(false);
    scanf("%d",&n);
    for (int i = 1; i <= n; i++) {
        scanf("%lf %lf",&s[i].x,&s[i].y);
    }
    random_shuffle(s + 1, s + n + 1);
    
    o = s[1];
    ri = 0;
    for (int i = 2; i <= n; i++) {
        if (dis(s[i], o) > ri + eps) {
            o = s[i];
            ri = 0;//第一个点为圆心
            for (int j = 1; j < i; j++) {
                if (dis(o, s[j]) > ri + eps) {
                    o.x = (s[i].x + s[j].x) / 2;
                    o.y = (s[i].y + s[j].y) / 2;
                    ri = dis(o, s[j]);//第一个点和第二个点中点为圆心,距离为直径
                    for (int k = 1; k < j; k++) {
                        if (dis(o, s[k]) > ri + eps) {
                            getr(s[i], s[j], s[k]);//三点定圆
                        }
                    }
                }
            }
        }
    }
    
    printf("%.10f\n",ri);
    printf("%.10f %.10f\n",o.x,o.y);
    return 0;
}
上一篇:BZOJ 4602: [Sdoi2016]齿轮


下一篇:803. 区间合并(贪心)