多邊形重心問題
- 描述
- 在某個多邊形上,取n個點,這n個點順序給出,按照給出順序將相鄰的點用直線連接, (第一個和最後一個連接),所有線段不和其他線段相交,但是可以重合,可得到一個多邊形或一條線段或一個多邊形和一個線段的連接後的圖形;
如果是一條線段,我們定義面積爲0,重心座標爲(0,0).現在求給出的點集組成的圖形的面積和重心橫縱座標的和;- 輸入
- 第一行有一個整數0<n<11,表示有n組數據;
每組數據第一行有一個整數m<10000,表示有這個多邊形有m個頂點; - 輸出
- 輸出每個多邊形的面積、重心橫縱座標的和,小數點後保留三位;
- 樣例輸入
-
3 3 0 1 0 2 0 3 3 1 1 0 0 0 1 4 1 1 0 0 0 0.5 0 1
- 樣例輸出
-
0.000 0.000 0.500 1.000 0.500 1.000
推廣至n邊形面積得:S = ((x1*y2 + x2*y3 + x3*y1)-(x2*y1 + x3*y2 + x1*y3)+ (x1*y3 + x3*y4 + x4*y1)-(x3*y1 + x4*y3 + x1*y4)+ ……)/ 2.0
化簡得:S = ((x1*y2 - x2*y1) + (x2*y3 - x3*y2) + …… + (xn*y1 - x1*yn))
三角形重心座標爲:x = (x1+x2+x3)/ 3.0 y = (y1+y2+y3)/ 3.0
但是不能直接推廣到n邊形重心,因爲重心是重量的重心,重量隨面積均勻分佈,要將面積作爲權值加入座標纔可以推廣至n邊形
即x = ((x1+x2)/ 3.0*S1 + (x2+x3)/ 3.0*S2 + ……)/ S
同理y = ((y1+y2)/ 3.0 *S1 + (y2+y3)/ 3.0*S2 + ……)/ S
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<vector>
#include<functional>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define CL(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
const int MOD = 1e9+7;
double X[maxn], Y[maxn];
int main(){
int t, n;
double area, s, xx, yy;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
xx = yy = area = s = 0;
for(int i = 0; i < n; i++) scanf("%lf%lf", &X[i], &Y[i]);
for(int i = 1; i <= n; i++){
area = (X[i-1]*Y[i%n] - X[i%n]*Y[i-1]) / 2.0;
s += area;
xx += area*(X[i%n] + X[i-1]) / 3.0;
yy += area*(Y[i%n] + Y[i-1]) / 3.0;
}
s = fabs(s);//s小於1e-4可看做除數爲0
if(s < 1e-4) printf("0.000 0.000\n");
else printf("%.3lf %.3lf\n", s, fabs(xx+yy)/s);
}
return 0;
}