多边形重心问题_nyoj_3(计算几何).java

来源:互联网 发布:桃园机场免税店mac 编辑:程序博客网 时间:2024/04/28 01:09

多边形重心问题

时间限制:3000 ms  |  内存限制:65535 KB
难度:5
描述
在某个多边形上,取n个点,这n个点顺序给出,按照给出顺序将相邻的点用直线连接, (第一个和最后一个连接),所有线段不和其他线段相交,但是可以重合,可得到一个多边形或一条线段或一个多边形和一个线段的连接后的图形; 
如果是一条线段,我们定义面积为0,重心坐标为(0,0).现在求给出的点集组成的图形的面积和重心横纵坐标的和;
输入
第一行有一个整数0<n<11,表示有n组数据;
每组数据第一行有一个整数m<10000,表示有这个多边形有m个顶点;
输出
输出每个多边形的面积、重心横纵坐标的和,小数点后保留三位;
样例输入
330 10 20 331 10 00 141 10 00 0.50 1
样例输出
0.000 0.0000.500 1.0000.500 1.000

import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);int n = input.nextInt();while (n-- > 0) {int m = input.nextInt();Shape[] arr = new Shape[m + 1];for (int i = 0; i < m; i++) {double x = input.nextDouble();double y = input.nextDouble();arr[i] = new Shape(x, y);}double area = 0.0;//多边形面积double Gx = 0.0, Gy = 0.0;// 重心的x、yfor (int i = 1; i <= m; i++) {double temp=(arr[i%m].x*arr[i-1].y-arr[i%m].y*arr[i-1].x)/2.0;area += temp;Gx += temp * (arr[i % m].x + arr[i - 1].x) / 3.0;Gy += temp * (arr[i % m].y + arr[i - 1].y) / 3.0;}if (area - 0 < 0.0000001) {System.out.println("0.000 0.000");continue;}System.out.print(String.format("%.3f %.3f\n",area,(Gx + Gy)/area));}}}class Shape {double x = 0;double y = 0;Shape(double x, double y) {this.x = x;this.y = y;}}