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;
}