NYOJ-3 多边形重心问题
2016-06-20 12:16
495 查看
NYOJ-3 多边形重心问题
解题思路么,主要就是向量X乘求面积咯,随便百度一下一大把,也容易理解,
说一下坑了我蛮久的问题,实在不吐不快
精度!精度!精度!
重要的事情说三遍!
好了,代码如下,
知道解题思路的话,理解代码还是很容易的,
如果感觉自己的思路没问题,那么可以参考一下问题大概在哪,,
提供两种思路吧,实则大同小异
方法一:
import java.text.DecimalFormat; import java.util.Scanner; public class Main { static class node{ public node(double x, double y) { this.x=x; this.y=y; } double x; double y; } public static void main(String[] args) { DecimalFormat decimalFormat=new DecimalFormat("0.000"); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m; node tempnode1; node tempnode2; node tempnode3; double area=0; double areatemp=0; double mid=0; for(int i=0;i<n;++i){ mid=0; area=0; m=sc.nextInt(); tempnode1=new node(sc.nextDouble(), sc.nextDouble()); tempnode2=new node(sc.nextDouble(), sc.nextDouble()); for(int j=2;j<m;++j){ tempnode3=new node(sc.nextDouble(), sc.nextDouble()); areatemp=((tempnode3.y-tempnode1.y)*(tempnode2.x-tempnode1.x)- (tempnode3.x-tempnode1.x)*(tempnode2.y-tempnode1.y) )/2; area+=areatemp; mid+=(tempnode1.x+tempnode1.y+tempnode2.x+tempnode2.y+tempnode3.x+tempnode3.y)/3*areatemp; tempnode2=tempnode3; } if(area!=0) mid/=area; else mid=0; area=Math.abs(area); System.out.println(decimalFormat.format(area)+" "+decimalFormat.format(mid)); } sc.close(); } }
方法二:
import java.text.DecimalFormat; import java.util.Scanner; public class Main { public static void main(String[] args) { DecimalFormat decimalFormat=new DecimalFormat("0.000"); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m; double area=0; double areatemp=0; double x1, y1, tempx, tempy, tempx1, tempy1 ; double mid=0; for(int i=0;i<n;++i){ area=0; mid=0; m=sc.nextInt(); x1=sc.nextDouble(); y1=sc.nextDouble(); tempx1=x1; tempy1=y1; for(int j=1;j<m;++j){ tempx=sc.nextDouble(); tempy=sc.nextDouble(); areatemp=(tempx*tempy1-tempy*tempx1)/2; area+=areatemp; mid+=areatemp*(tempx+tempy+tempx1+tempy1)/3; tempx1=tempx; tempy1=tempy; } areatemp=(x1*tempy1-y1*tempx1)/2; area+=areatemp; mid+=areatemp*(tempx1+tempy1+x1+y1)/3; if(area>=0.001) mid/=area; else mid=0; area=Math.abs(area); System.out.println(decimalFormat.format(area)+" "+decimalFormat.format(mid)); } sc.close(); } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树