题目链接
知识讲解
两种代码~
#include<stdio.h> #include<iostream> #include<cmath> using namespace std; const double eps=1e-7; int cmp(double a){ if(fabs(a)<eps)return 0; else return 1; } struct node{ double x,y; node(){} node(double a,double b):x(a),y(b){} friend node operator +(const node &a, const node &b){ return node( a.x+b.x, a.y+b.y); } friend node operator -(const node &a, const node &b){ return node( a.x-b.x, a.y-b.y); } friend node operator *(const node &a, const double &b ){ return node( a.x*b, a.y*b); } friend node operator *(const double &b , const node &a ){ return node( a.x*b, a.y*b); } friend node operator /(const node a,const double &b){ return node( a.x/b, a.y/b); } }; double fabs_det(node a,node b){ //求面积 return a.x*b.y-a.y*b.x; } struct convex{ node point[1200000]; int n; double area(){ point[n]=point[0]; double sum=0; for(int i=0;i<n;i++){ sum+= (point[i].x*point[i+1].y-point[i].y*point[i+1].x); } return sum/2; } node get_point(){ node ans(0,0); //point[n]=point[0]; for(int i=1;i<n-1;i++){ ans=ans+fabs_det(point[i]-point[0],point[i+1]-point[0])*(point[i+1]+point[i]+point[0]); //这里的叉积和面积都不要求绝对指 } return ans/ (area()*6); } }shape; int main() { int x; scanf("%d",&x); while(x--){ scanf("%d",&shape.n); for (int i=0;i<shape.n;i++){ scanf("%lf%lf",&shape.point[i].x,&shape.point[i].y); } //printf("%lf\n",shape.area()); node ans=shape.get_point(); printf("%.2lf %.2lf\n",cmp(ans.x)==0?0.00:ans.x,cmp(ans.y)==0?0.00:ans.y); } return 0; }
#include<stdio.h> #include<iostream> #include<cmath> using namespace std; const double eps=1e-7; int cmp(double a){ if(fabs(a)<eps)return 0; else return 1; } struct node{ double x,y; node(){} node(double a,double b):x(a),y(b){} friend node operator +(const node &a, const node &b){ //重载对点的运算 return node( a.x+b.x, a.y+b.y); } friend node operator -(const node &a, const node &b){ return node( a.x-b.x, a.y-b.y); } friend node operator *(const node &a, const double &b ){ return node( a.x*b, a.y*b); } friend node operator *(const double &b , const node &a ){ return node( a.x*b, a.y*b); } friend node operator /(const node &a,const double &b){ return node( a.x/b, a.y/b); } }; double det(node a,node b){ //求面积 叉积 return a.x*b.y-a.y*b.x; } struct convex{ node point[1200000]; int n; double area(){ point[n]=point[0]; double sum=0; for(int i=0;i<n;i++){ sum+= (point[i].x*point[i+1].y-point[i].y*point[i+1].x); } return sum/2; } node get_point(){ node ans(0,0); point[n]=point[0]; for(int i=0;i<n;i++){ ans=ans+ (point[i]+point[i+1]) * det(point[i],point[i+1]) ; //不要求绝对值 } return ans/ (area()*6); } }shape; int main() { int x; scanf("%d",&x); while(x--){ scanf("%d",&shape.n); for (int i=0;i<shape.n;i++){ scanf("%lf%lf",&shape.point[i].x,&shape.point[i].y); } //printf("%lf\n",shape.area()); node ans=shape.get_point(); printf("%.2lf %.2lf\n",cmp(ans.x)==0?0.00:ans.x,cmp(ans.y)==0?0.00:ans.y); } return 0; }