题意:求一个n边形重心(n <= 100)。
题目链接:http://poj.org/problem?id=3855
——>>一道几何模版题,敲了3份模版,坑了近5个小时,最后3分钟A过……
其实所有的解法就一个问题:当重心为(0, 0)时,若以 %lf 输出,可能会出现-0.000000的情况,而正解应为0.000000,此时,用 %f 输出就能避免这个问题(最后发现,师弟的写法较赛时我所敲的3份模版都要精辟,学习了~)。
#include <cstdio>using namespace std;const int maxn = 100 + 10;
int n, kase = 1;struct Point{double x, y;Point(double x = 0, double y = 0):x(x), y(y){}
}v[maxn];double Cross(Point A, Point B){ //叉积,三角形有向面积的2倍return A.x * B.y - B.x * A.y;
}Point barycenter(Point p[], int n){Point ret;double area = 0;for(int i = 1; i < n; i++){double area2 = Cross(p[i-1], p[i]); //上下都取面积的2倍,最后会被约掉的ret.x += (p[i-1].x + p[i].x) / 3 * area2;ret.y += (p[i-1].y + p[i].y) / 3 * area2;area += area2;}double area2 = Cross(p[n-1], p[0]);ret.x += (p[n-1].x + p[0].x) / 3 * area2;ret.y += (p[n-1].y + p[0].y) / 3 * area2;area += area2;ret.x /= area;ret.y /= area;return ret;
}void read(){for(int i = 0; i < n; i++) scanf("%lf%lf", &v[i].x, &v[i].y);
}void solve(){Point ret = barycenter(v, n);printf("Stage #%d: %.6f %.6f\n", kase++, ret.x, ret.y);
}int main()
{while(scanf("%d", &n) == 1 && n){read();solve();}return 0;
}