题目描述
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
题解
这道题目的意思就是要你求出一个多边形的重心。
要求这个东西首先我们要明确一个概念:带权点集重心
带权点集重心实际上就是所有点的加权平均值,具体来说看下面公式:
这里的 xi,yi x i , y i 是每个点的横纵坐标, mi m i 是每个点的权值,这个就是加权平均值。
那么还有一个东西:三角形的重心怎么求呢?
初中应该就学过,三角形的内心就是三角形三个点的横纵坐标的平均值,也就是这个:
而 n n 边形显然可以划分成个三角形,所以多边形的重心就是这 (n−2) ( n − 2 ) 个三角形的重心以这 (n−2) ( n − 2 ) 个三角形的面积为权值的带权点集重心,通过上面两个公式,这个就好求了吧。。。
这道题目就做完了。。。下面放代码(代码超级短):
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define maxn 1000010
using namespace std;
int T,n;
struct P{
double x,y;
}a[maxn];
P operator - (P a,P b)
{
P tmp;
tmp.x=a.x-b.x;tmp.y=a.y-b.y;
return tmp;
}
double operator * (P a,P b)
{
return a.x*b.y-b.x*a.y;
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%lf%lf",&a[i].x,&a[i].y);
double S=0.0,X=0.0,Y=0.0;
for(int i=2;i<n;i++)
{
double x=(a[i]-a[1])*(a[i+1]-a[1]);
X+=(a[1].x+a[i].x+a[i+1].x)*x;
Y+=(a[1].y+a[i].y+a[i+1].y)*x;
S+=x;
}
printf("%.2lf %.2lf\n",X/S/(double)3,Y/S/(double)3);
}
return 0;
}
谢谢大家!!