NYOJ-多边形重心问题(计算几何)

多边形重心问题

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


import java.util.Scanner;
import java.text.DecimalFormat;


//定义坐标
class Point {
	double x;
	double y;
}

public class Main {
	static Point[] p;
	static DecimalFormat df = new DecimalFormat("#0.000"); // 保留小数后三位小数

	public static double getArea(Point p1, Point p2) {
		return p1.x * p2.y - p1.y * p2.x;
	}

	public static void main(String args[]) {
		@SuppressWarnings("resource")
		Scanner cin = new Scanner(System.in);
		int n, m, i; // m顶点个数
		double x, y, s, t;  //重心(x, y), 面积s, // 各个三角形的有向面积t
		n = cin.nextInt();
		while (n-- != 0) {
			m = cin.nextInt();
			p = new Point[m + 1];
			for (i = 0; i < m; i++) {
				p[i] = new Point();
				p[i].x = cin.nextDouble();
				p[i].y = cin.nextDouble();
			}
			p[m] = p[0];
			s = x = y = 0.0;
			for (i = 0; i < m; i++) {
				t = getArea(p[i], p[i + 1]) / 2.0;
				s += t;        
				x += t * (p[i].x + p[i + 1].x) / 3.0;
				y += t * (p[i].y + p[i + 1].y) / 3.0;
			}
			if (Math.abs(s - 0) < 0.0000001)
				System.out.println("0.000 0.000");
			else
				System.out.println(df.format(Math.abs(s)) + " "
						+ df.format(Math.abs((x + y) / s)));
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值