这题调了N久啊有木有,交到hdu都AC了的代码,在BIT就是WA,我调了三个小时了有木有
问题:
已知多边形的各点的坐标
计算一个多边形的重心的坐标,多边形的质量分布均匀
按逆时针顺序给出各个点的坐标
如图
将多边形作如图切割,红点是各个三角形的重心,连起来就是另一个多边形
将各个三角形看成一个点,即整个三角形的重量都集中在一个点上
然后求各个重心所构成的多边形的重心
例如,各个重心的坐标为(x1,y2)(x2,y2)...(xn,yn)
各个重心的重量为w1,w2,,,,,wn
多边形的重心为X,Y
X=(x1*w1+x2*w2+....+xn*wn)/n
Y=(y1*w1+y2*w2+.....+yn*wn)/n
接下来上代码
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
class point//坐标
{
public:
double x,y;
};
class Vector//向量
{
public:
double x,y;
double cross(Vector a)//叉积
{
return x*a.y-a.x*y;
}
};
Vector operator-(point a,point b)
{
Vector res;
res.x=a.x-b.x;
res.y=a.y-b.y;
return res;
}
point CalcCenter(point a,point b,point c)
{
point res;
res.x=(a.x+b.x+c.x);
res.y=(a.y+b.y+c.y);
return res;
}
int main()
{
int n;
while (~scanf("%d",&n))
{
point ans;
ans.x=0;
ans.y=0;
double sumWeight=0;
point a,b,c;
scanf("%lf %lf",&a.x,&a.y);
scanf("%lf %lf",&b.x,&b.y);
scanf("%lf %lf",&c.x,&c.y);
Vector t1,t2;
t1=b-a;
t2=c-a;
point p=CalcCenter(a,b,c);
double area=t1.cross(t2);
ans.x+=p.x*area;
ans.y+=p.y*area;
sumWeight+=area;
for (int i = 3; i < n; i++)
{
point temp;
scanf("%lf %lf",&temp.x,&temp.y);
t1=t2;
t2=temp-a;
b=c;
c=temp;
p=CalcCenter(a,b,c);
area=t1.cross(t2);
ans.x+=area*p.x;
ans.y+=area*p.y;
sumWeight+=area;
}
ans.x/=sumWeight;
ans.y/=sumWeight;
printf("%.2lf %.2lf\n",ans.x/3+0.00000001,ans.y/3+0.00000001);//不加这个0.00000000001就会出现输出-0.0的情况,在hdu可以ac,在bit就wa了
}
return 0;
}