Address:http://acm.nyist.net/JudgeOnline/problem.php?pid=3
由于LZ最近在看计算几何,昨天让队友帮我看个题目,他说nyoj上的第三题让他很无语。LZ就来试一试。拿着刚学的知识模版套用上去,思路是正确的。但是没有AC,后来看了讨论区的才知道需要判断 if(S<0.00001&&S>-0.00001) cout<<"0.000 0.000"<<endl; (没有这个判断,就会WR),我在网上看别的友友 判断的时候用了0.0000001,到现在还不是太懂这个判断。
自己刚开始模版套上去的代码,(后面是自己把代码精简后的,因为求重心和面积的时候中间有求共同的结果)
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
typedef struct
{
double x,y;
}Point;
Point p[10010];
double s;
int n;
double area()
{
int k;
p[n]=p[0];
s=0;
if(n<3) return 0;
for(k=0;k<n;k++)
{
s+=p[k].x*p[k+1].y;
s-=p[k+1].x*p[k].y;
}
s/=2;
return (s>0?s:-s);
}
Point gravi()
{
p[n]=p[0];
double A,a;
Point t;
int j;
t.x=0; t.y=0; A=0;
for(j=0;j<n;j++)
{
a=p[j].x*p[j+1].y-p[j+1].x*p[j].y;
t.x+=(p[j].x+p[j+1].x)*a;
t.y+=(p[j].y+p[j+1].y)*a;
A+=a;
}
if(A==0) return t;
t.x /= A*3;
t.y /= A*3;
return t;
}
int main()
{
int T;
cin>>T;
Point z;
while(T--)
{
int i;
cin>>n;
for(i=0;i<n;i++)
cin>>p[i].x>>p[i].y;
double S=area();
if(S<0.00001&&S>-0.00001)
cout<<"0.000 0.000"<<endl;
else
{
printf("%.3lf ",S);
z=gravi();
printf("%.3lf\n",z.x+z.y);
}
}
return 0;
}
简短。
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
struct Point
{
double x,y;
}p[10010];
int n;
int main()
{
int T;
cin>>T;
while(T--)
{
int i,j,k;
cin>>n;
for(i=0;i<n;i++)
cin>>p[i].x>>p[i].y;
double S,A,a;
Point t; t.x=0; t.y=0; S=0;
p[n]=p[0];
for(i=0;i<n;i++)
{
a=(p[i].x*p[i+1].y-p[i+1].x*p[i].y)/2.0;
S+=a;
t.x+=a*(p[i].x+p[i+1].x)/3.0;
t.y+=a*(p[i].y+p[i+1].y)/3.0;
}
A=t.x+t.y;
if(fabs(S)<1e-6)
{
cout<<"0.000 0.000"<<endl;
}
else
{
printf("%.3lf %.3lf\n",fabs(S),A/S);
}
}
return 0;
}