题目描述
There are many secret openings in the floor which are covered by a big heavy stone. When the stone is lifted up, a special mechanism detects this and activates poisoned arrows that are shot near the opening. The only possibility is to lift the stone very slowly and carefully. The ACM team must connect a rope to the stone and then lift it using a pulley. Moreover, the stone must be lifted all at once; no side can rise before another. So it is very important to find the centre of gravity and connect the rope exactly to that point. The stone has a polygonal shape and its height is the same throughout the whole polygonal area. Your task is to find the centre of gravity for the given polygon.
Input
The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing a single integer N (3 <= N <= 1000000) indicating the number of points that form the polygon. This is followed by N lines, each containing two integers Xi and Yi (|Xi|, |Yi| <= 20000). These numbers are the coordinates of the i-th point. When we connect the points in the given order, we get a polygon. You may assume that the edges never touch each other (except the neighboring ones) and that they never cross. The area of the polygon is never zero, i.e. it cannot collapse into a single line.
Output
Print exactly one line for each test case. The line should contain exactly two numbers separated by one space. These numbers are the coordinates of the centre of gravity. Round the coordinates to the nearest number with exactly two digits after the decimal point (0.005 rounds up to 0.01). Note that the centre of gravity may be outside the polygon, if its shape is not convex. If there is such a case in the input data, print the centre anyway.
Sample Input
2
4
5 0
0 5
-5 0
0 -5
4
1 1
11 1
11 11
1 11
Sample Output
0.00 0.00
6.00 6.00
分析
有一个密度均匀的平面N多边形(3 <= N <= 1000000),可能凹也可能凸,但没有边相交叉,要求我们求多边形的重心坐标。
带权点集重心实际上就是所有点的加权平均值,具体来说看下面公式:
这里的xi,yi是每个点的横纵坐标,mi是每个点的权值,这个就是加权平均值。
三角形的重心坐标就是三角形三个点的横纵坐标的平均值:
而n边形显然可以划分成(n−2)个三角形,所以多边形的重心就是这(n−2)个三角形的重心以这(n−2)个三角形的面积为权值的带权点集重心。
不必在求每个小三角形的重心时都除以3,可以在最后除。
C++ 代码
#include<bits/stdc++.h>
using namespace std;
int n,T;
struct node{
double x,y;
}p0,p1,p2,center;
double Area(node p,node a,node b) //叉积求三角形面积
{
double S=(a.x-p.x)*(b.y-p.y)-(b.x-p.x)*(a.y-p.y);
S/=2;
return S;
}
int main()
{
scanf("%d", &T);
while(T--)
{
double sumA=0,sumx=0,sumy=0,area;
center.x=0,center.y=0;
scanf("%d", &n);
scanf("%lf%lf", &p0.x, &p0.y); //先输入两个点
scanf("%lf%lf", &p1.x, &p1.y);
for(int i=3;i<=n;i++)
{
scanf("%lf%lf", &p2.x, &p2.y);
center.x=(p0.x+p1.x+p2.x); //当前三角形重心为三点之和,不必现在除3
center.y=(p0.y+p1.y+p2.y);
area=Area(p0,p1,p2); //求解面积作为当前三角形的权值
sumA+=area; //计算总面积
sumx+=center.x*area; //带权点集重心X坐标=当前三角形重心X坐标*面积权值
sumy+=center.y*area; //带权点集重心Y坐标=当前三角形重心Y坐标*面积权值
p1=p2; //为了求之后的三角形面积,需要把p2变成p1
}
printf("%.2lf %.2lf\n",sumx/sumA/3,sumy/sumA/3); //计算最后的重心坐标
}
return 0;
}
单词好多 英语这门语言确实比中文长啊
注释好评👍
谢谢 :)