Lifting the Stone HDU - 1115 求多边形的重心
InputThe 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.
OutputPrint 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
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll inf = 4e18+10; const int mod = 1000000007; const int mx = 5e6+5; //check the limits, dummy typedef pair<int, int> pa; const double PI = acos(-1); ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } #define swa(a,b) a^=b^=a^=b #define re(i,a,b) for(int i=(a),_=(b);i<_;i++) #define rb(i,a,b) for(int i=(b),_=(a);i>=_;i--) #define clr(a) memset(a, 0, sizeof(a)) #define lowbit(x) ((x)&(x-1)) #define mkp make_pair void sc(int& x) { scanf("%d", &x); }void sc(int64_t& x) { scanf("%lld", &x); }void sc(double& x) { scanf("%lf", &x); }void sc(char& x) { scanf(" %c", &x); }void sc(char* x) { scanf("%s", x); } struct point { double x, y; point(double X = 0, double Y = 0) { x = X; y = Y; } point operator + (point B) { return point(x + B.x, y + B.y); } point operator - (point B) { return point(x - B.x, y - B.y); } point operator * (double k) { return point(x * k, y * k); } point operator / (double k) { return point(x / k, y / k); } }; typedef point Vector; double cross(Vector A, Vector B) { return A.x * B.y - A.y * B.x; } double area(point *p, int n) { double area = 0; re(i, 0, n) area += cross(p[i], p[(i + 1) % n]); return area / 2;//面积有正负,不能取绝对值 } point Center(point *p, int n) { point ans(0, 0); if(area(p,n)==0)return ans; re(i, 0, n) ans = ans + (p[i] + p[(i + 1) % n]) * cross(p[i], p[(i + 1) % n]); return ans / area(p, n) / 6; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t, n, i; point center; point p[100000]; sc(t); while (t--) { sc(n); re(i, 0, n)sc(p[i].x), sc(p[i].y); center = Center(p, n); printf("%.2f %.2f\n", center.x, center.y); } return 0; }