(笔试)寻找三角形

mac2025-02-15  8

题目

三维空间中有N个点,每个点可能是三种颜色的其中之一,三种颜色分别是红绿蓝,分别用’R’, ‘G’, 'B’表示。 现在要找出三个点,并组成一个三角形,使得这个三角形的面积最大。 但是三角形必须满足:三个点的颜色要么全部相同,要么全部不同。

输入用例 5 R 0 0 0 R 0 4 0 R 0 0 3 G 92 14 7 G 12 16 8 输出

6.00000

思路: 这个题,难点在于如何求出空间内三点确定的三角形面积,有两种方法: 第一种 比较麻烦,先用两个点A,B确定一条直线方程,再求出它的法线的斜率,再让另外一点C经过该斜率的直线就能确定法线的方程,两个方程连立得到交点D,AB间距离就是三角形的底,CD就是三角形的高,(AB*CD)/2就得到了三角形面积 第二种 利用海伦公式,空间内三点确定的三角形面积S = √p(p-a)(p-b)(p-c), 就可求出三角形面积

代码:

import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Scanner; public class TriangleArea { public static class Point{ double x,y,z; String color; public Point(String color,double x,double y,double z) { this.x = x; this.y = y; this.z = z; this.color = color; } } public static double calculateArea(Point a,Point b,Point c) { double length1 = Math.sqrt(Math.pow(a.x-b.x, 2)+Math.pow(a.y-b.y, 2)+Math.pow(a.z-b.z, 2)); double length2 = Math.sqrt(Math.pow(a.x-c.x, 2)+Math.pow(a.y-c.y, 2)+Math.pow(a.z-c.z, 2)); double length3 = Math.sqrt(Math.pow(b.x-c.x, 2)+Math.pow(b.y-c.y, 2)+Math.pow(b.z-c.z, 2)); if(length1+length2>length3&&length2+length3>length1&&length1+length3>length2) { double p = (length1+length2+length3)/2; double s = Math.sqrt(p*(p-length1)*(p-length2)*(p-length3)); return s; } return 0; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); ArrayList<Point> list = new ArrayList<>(); for(int i=0;i<count;i++) { String color = sc.next(); double x = sc.nextDouble(); double y = sc.nextDouble(); double z = sc.nextDouble(); Point tmp = new Point(color,x,y,z); list.add(tmp); } sc.close(); double mix = 0.00000; for(int i=0;i<list.size();i++) { for(int j=0;j<list.size()&&j!=i;j++) { for(int k=0;k<list.size()&&k!=j&&k!=i;k++) { Point a = list.get(i); Point b = list.get(j); Point c = list.get(k); if((a.color.equals(b.color)&&b.color.equals(c.color))||!(a.color.equals(b.color))&&!(a.color.equals(c.color))&&!(b.color.equals(c.color))) { double s = calculateArea(a, b, c); if(s>mix) { mix = s; } } } } } DecimalFormat df = new DecimalFormat("0.00000"); System.out.println(df.format(mix)); } }
最新回复(0)