【模拟试题】多边形的重心
Description
给出n个顶点的多边形(有凸有凹)的顶点坐标(顺时针给出),求这个多边形的重心坐标
You're given a vertex sequence of a simple polygon with N verteces.
The task is to find the centre of gravity of the polygon.
You're given a vertex sequence of a simple polygon with N verteces.
The task is to find the centre of gravity of the polygon.
Input
第一行一个整数n,表示这是n多边形
以下2到n+1行,第i+1行给出两个整数,分别是该顶点的x,y坐标
以下2到n+1行,第i+1行给出两个整数,分别是该顶点的x,y坐标
Output
只有一行,输出两个实数(保留两位小数),表示重心的x,y坐标
Sample Input
4
0 0
0 4
4 4
4 0
Sample Output
2.00 2.00
Hint
【数据规模】
3 ≤ n ≤ 1,000,000
每个顶点坐标不会超过2^31
3 ≤ n ≤ 1,000,000
每个顶点坐标不会超过2^31
Solution
求一个不规则多边形的重心。
由于我们大部分的算法都是基于凸多边形的基础才衍生出来的,所以这道题我们可以先将不规则的多边形分割为n-2个三角形。分别求出每一个三角形的面积和中心,又因为这个多边形是均匀的,所以可以用面积加权求出多边形的重心。
CODE
这个数据简直是。。。吓得我乱开long long 和long double。。。
#include<iostream>
#include<cstdio>
using namespace std;
int main() {
long long i,j,k,n,T;
long double sumx,sumy,suma;
long double x0,y0,x1,y1,x2,y2;
long double x,y,s;
scanf("%lld",&n);
scanf("%Lf%Lf%Lf%Lf",&x0,&y0,&x1,&y1);
sumx=sumy=suma=0;
for(i=2; i<n; i++) {
scanf("%Lf%Lf",&x2,&y2);
x=x0+x1+x2;y=y0+y1+y2;
s=x0*y1+x1*y2+x2*y0-x1*y0-x2*y1-x0*y2;
suma+=s;
sumx+=s*x;sumy+=s*y;
x1=x2;y1=y2;
}
printf("%.2Lf %.2Lf",sumx/suma/3,sumy/suma/3);
return 0;
}