UVa 10002 Center of Masses (凸包重心)

262 篇文章 0 订阅
40 篇文章 0 订阅

http://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=943


重心=(多边形三角剖分的各个三角形的重心*各个三角形的有向面积/多边形面积)/3


完整代码:

/*0.095s*/

#include<bits/stdc++.h>
using namespace std;
const int mx = 105;
const double eps = 1e-8;

struct P
{
	double x, y;
	P(double x = 0, double y = 0): x(x), y(y) {}
	void read()
	{
		scanf("%lf%lf", &x, &y);
	}
	bool operator < (const P& p) const ///加cosnt以便sort调用,其他函数不加const对速度没有影响
	{
		return x < p.x || x == p.x && y < p.y;
	}
	P operator + (P p)
	{
		return P(x + p.x, y + p.y);
	}
	P operator - (P p)
	{
		return P(x - p.x, y - p.y);
	}
	P operator * (double d)
	{
		return P(x * d, y * d);
	}
	P operator / (double d)
	{
		return P(x / d, y / d);
	}
	double dot(P p)
	{
		return x * p.x + y * p.y;
	}
	double det(P p)
	{
		return x * p.y - y * p.x;
	}
} a[mx], ans[mx];

int n, len;

///求凸包
void convex_hull()
{
	sort(a, a + n);
	len = 0;
	int i;
	for (i = 0; i < n; ++i)
	{
		while (len >= 2 && (ans[len - 1] - ans[len - 2]).det(a[i] - ans[len - 1]) < eps)
			--len;
		ans[len++] = a[i];
	}
	int tmp = len;
	for (i = n - 2; i >= 0; --i)
	{
		while (len > tmp && (ans[len - 1] - ans[len - 2]).det(a[i] - ans[len - 1]) < eps)
			--len;
		ans[len++] = a[i];
	}
	--len;
}

double area()
{
	double sum = 0.0;
	ans[n] = ans[0];
	for (int i = 0; i < len; ++i)
		sum += ans[i].det(ans[i + 1]);
	return sum / 2.0;
}

P masscenter()
{
	P res = P(0, 0);
	double s = area();
	if (s < eps) return res;
	ans[n] = ans[0];
	for (int i = 0; i < len; ++i)
		res = res + (ans[i] + ans[i + 1]) * (ans[i].det(ans[i + 1]));
	return res / s / 6.0; ///((res/2)/s)/3
}

int main()
{
	int i;
	P res;
	while (scanf("%d", &n), n >= 3)
	{
		for (i = 0; i < n; ++i) a[i].read();
		convex_hull();
		res = masscenter();
		printf("%.3f %.3f\n", res.x, res.y);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值