Geometry Problem HDU - 6242(随机+三点共圆)

题意:在一个二维平面中给出n个点,让你找到一个圆心和一个半径,使得 ⌈ n 2 ⌉ \lceil \frac{n}{2} \rceil 2n 个点在这个圆上。保证答案一定存在。

思路:可以知道三点确定一个圆,我们可以通过枚举三个点然后判断当前圆是否符合要求。思路是这个思路,但是1e5个点不允许这么做。仔细想一想答案一定存在的情况下我从n个点中取一个出来至少有 1 2 \frac{1}{2} 21 的概率可以选中这个圆上的点。所以我通过随机的方法来选出三个点,每一次选三个点在圆上的概率就是 1 8 \frac{1}{8} 81 ,循环次数不需要很多次就可以找得到答案了。还有就是需要讨论 n = 1, n = 2的时候,直接选择一个点在圆上就可以了,对于 n = 3, n = 4 的情况,令随便两个点作为直径搞一下就可以了。

#include <iostream>
#include <cmath>
#include <time.h>
using namespace std;
const double eps = 1e-8;

double sgn(double x) {
	if(fabs(x) < eps) return 0;
	if(x < 0) return -1;
	else return 1;
}

struct Point { // 表示点
	double x, y;
	Point(){}
	Point(double _x,double _y) {
		x = _x; y = _y;
	}
	Point operator - (const Point &b) const {
		return Point(x - b.x,y - b.y);
	}
	double operator * (const Point &b) const {
		return x*b.x + y*b.y;
	}
};

//两点距离
double dist(Point a,Point b) {
	return sqrt((b-a)*(b-a));
}

Point solve(Point a, Point b, Point c) { // 三点共圆圆心公式
	double X, Y;
	double fm1=2 * (a.y - c.y) * (a.x - b.x) - 2 * (a.y - b.y) * (a.x - c.x);
	double fm2=2 * (a.y - b.y) * (a.x - c.x) - 2 * (a.y - c.y) * (a.x - b.x);
	if (fm1 == 0 || fm2 == 0) {
		X = Y = 1e18;
		return Point(X, Y);
	}
	double fz1=a.x * a.x - b.x * b.x + a.y * a.y - b.y * b.y;
	double fz2=a.x * a.x - c.x * c.x + a.y * a.y - c.y * c.y;
	X = (fz1 * (a.y - c.y) - fz2 * (a.y - b.y)) / fm1;
	Y = (fz1 * (a.x - c.x) - fz2 * (a.x - b.x)) / fm2;
	
	return Point(X, Y);
}

int _, n;
Point p[100005];

bool check(Point cen, double r) {
	int res = 0;
	for(int i = 1;i <= n; i++) {
		if(sgn(dist(cen, p[i]) - r) == 0) {
			res++;
			if(res >= (n+1)/2) break;
		} 
	}
	return res >= (n + 1) / 2;
}

int main() {
	srand(time(NULL));
	scanf("%d", &_);
	while(_--) {
		scanf("%d", &n);
		for(int i = 1;i <= n; i++) {
			scanf("%lf %lf", &p[i].x, &p[i].y);
		}
		if(n == 1 || n == 2) {
			printf("%lf %lf 1.0\n", p[1].x+1, p[1].y);
			continue;
		}
		if(n == 3 || n == 4) {
			printf("%lf %lf %lf\n", (p[1].x+p[2].x)/2, (p[1].y+p[2].y)/2, dist(p[1], p[2])/2);
			continue;
		}
		
		Point ansp; double ansr;
		while (1) {
			int one = rand() % n + 1;
			int two = rand() % n + 1;
			int three = rand() % n + 1;
			if(one == two || two == three || one == three) continue;
			Point cen = solve(p[one], p[two], p[three]);
			if(cen.x == 1e18) continue;
			double r = dist(cen, p[one]);
			
			if(check(cen, r)) {
				ansp = cen; ansr = r;
				break;
			}
		}
		
		if(sgn(ansp.x-0.0) == 0) ansp.x = 0;
		if(sgn(ansp.y-0.0) == 0) ansp.y = 0;
		printf("%lf %lf %lf\n", ansp.x, ansp.y, ansr);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值