UVA 10002 Center of Masses

给你一个凸多边形的点(又是无序),求质心。

 

质心和重心有什么区别呢?百度了下,发现,如果重力场均匀的话,这俩心重合。

 

那直接求重心好了。

 

因为无序,所以需要用凸包求下,然后再求重心。

 

#include <queue> #include <stack> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <limits.h> #include <string.h> #include <string> #include <algorithm> using namespace std; const int MAX = 110; struct point{ double x,y;}; point c[MAX]; const double eps = 1e-6; bool dy(double x,double y) { return x > y + eps;} // x > y bool xy(double x,double y) { return x < y - eps;} // x < y bool dyd(double x,double y) { return x > y - eps;} // x >= y bool xyd(double x,double y) { return x < y + eps;} // x <= y bool dd(double x,double y) { return fabs( x - y ) < eps;} // x == y double crossProduct(point a,point b,point c) { return (c.x - a.x)*(b.y - a.y) - (b.x - a.x)*(c.y - a.y); } point bary_center(point p[],int n) { point ans,t; double area = 0.0,t2; ans.x = 0.0; ans.y = 0.0; for(int i=1; i<n-1; i++) { t2 = crossProduct(p[i],p[0],p[i+1])/2.0; ans.x += (p[0].x + p[i].x + p[i+1].x)*t2; ans.y += (p[0].y + p[i].y + p[i+1].y)*t2; area += t2; } ans.x /= (3*area); ans.y /= (3*area); return ans; } double disp2p(point a,point b) { return sqrt( ( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y ) ); } bool cmp(point a,point b) // 排序 { double len = crossProduct(c[0],a,b); if( dd(len,0.0) ) return xy(disp2p(c[0],a),disp2p(c[0],b)); return xy(len,0.0); } point stk[MAX]; int top; void Graham(int n) { int tmp = 0; for(int i=1; i<n; i++) if( xy(c[i].x,c[tmp].x) || dd(c[i].x,c[tmp].x) && xy(c[i].y,c[tmp].y) ) tmp = i; swap(c[0],c[tmp]); sort(c+1,c+n,cmp); stk[0] = c[0]; stk[1] = c[1]; top = 1; for(int i=2; i<n; i++) { while( xyd( crossProduct(stk[top],stk[top-1],c[i]), 0.0 ) && top >= 1 ) top--; stk[++top] = c[i]; } point ans = bary_center(stk,top+1); printf("%.3lf %.3lf/n",ans.x,ans.y); } int main() { int n; while( ~scanf("%d",&n) && n >= 3 ) { for(int i=0; i<n; i++) scanf("%lf%lf",&c[i].x,&c[i].y); Graham(n); } return 0; }  

你可能感兴趣的:(UVA 10002 Center of Masses)