Skip to content

Commit 847ca7a

Browse files
committed
求任意多边形重心(附HDU - 1115 Lifting the Stone代码)
1 parent f355ee2 commit 847ca7a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Centre-of-Gravity(Polygon).cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include <cstdio>
2+
3+
using namespace std;
4+
5+
struct point
6+
{
7+
double x, y;
8+
point(double _x = 0, double _y = 0) : x(_x), y(_y) { }
9+
}d[1000010];
10+
11+
int t, n;
12+
13+
inline double abs(double x)
14+
{
15+
return x < 0 ? -x : x;
16+
}
17+
18+
inline point operator - (const point &a, const point &b)
19+
{
20+
return point(a.x - b.x, a.y - b.y);
21+
}
22+
23+
inline double cross(const point &a, const point &b)
24+
{
25+
return a.x * b.y - a.y * b.x;
26+
}
27+
28+
inline double area(const point &a, const point &b, const point &c)
29+
{
30+
return cross(b - a, c - a) / 2.0;
31+
}
32+
33+
int main()
34+
{
35+
scanf("%d", &t);
36+
while (t--)
37+
{
38+
scanf("%d", &n);
39+
for (int i = 0; i < n; i++)
40+
{
41+
scanf("%lf%lf", &d[i].x, &d[i].y);
42+
}
43+
double sumx = 0, sumy = 0, areasum = 0;
44+
for (int i = 2; i < n; i++)
45+
{
46+
double a = area(d[0], d[i - 1], d[i]);
47+
sumx += (d[0].x + d[i - 1].x + d[i].x) / 3.0f * a;
48+
sumy += (d[0].y + d[i - 1].y + d[i].y) / 3.0f * a;
49+
areasum += a;
50+
}
51+
printf("%.2lf %.2lf\n", sumx / areasum + 1e-8, sumy / areasum + 1e-8);
52+
}
53+
return 0;
54+
}

0 commit comments

Comments
 (0)