题目:
三维空间中有N个点,每个点可能是三种颜色的其中之一,三种颜色分别是红绿蓝,分别用’R’, ‘G’, 'B’表示。
现在要找出三个点,并组成一个三角形,使得这个三角形的面积最大。
但是三角形必须满足:三个点的颜色要么全部相同,要么全部不同。
思路:
笨办法,利用海伦公式,各种点的组合逐个判断。
代码实现:
#include <iostream>
#include <vector>
#include <math.h>
#include <iomanip>
using namespace std;
struct Point{
char c;
int x, y, z;
};
double count_triangle_area(const Point &a,const Point &b,const Point &c){
double area = -1;
double side[3];//存储三条边的长度;
side[0] = sqrt(pow(a.x - b.x,2)+pow(a.y - b.y,2) + pow(a.z - b.z,2));
side[1] = sqrt(pow(a.x - c.x,2)+pow(a.y - c.y,2) + pow(a.z - c.z,2));
side[2] = sqrt(pow(c.x - b.x,2)+pow(c.y - b.y,2) + pow(c.z - b.z,2));
//不能构成三角形;
if(side[0]+side[1]<=side[2] || side[0]+side[2]<=side[1] || side[1]+side[2]<=side[0]) return area;
//利用海伦公式。s=sqr(p*(p-a)(p-b)(p-c));
double p = (side[0]+side[1]+side[2])/2; //半周长;
area = sqrt(p*(p-side[0])*(p-side[1])*(p-side[2]));
return area;
/*
————————————————
版权声明:本文为CSDN博主「deeebug」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hjq376247328/article/details/49465137
*/
}
bool checkColor(const Point &a,const Point &b,const Point &c){
return ((a.c==b.c)&&(a.c==c.c)&&(b.c==c.c))||((a.c!=b.c)&&(a.c!=c.c)&&(b.c!=c.c));
}
int main(){
int n;
cin >> n;
vector<Point> points;
for (int i = 0; i < n; ++i){
char c;
int x, y, z;
cin >> c >> x >> y >> z;
points.push_back({c,x,y,z});
}
double max_area = 0.0;
for (int i = 0; i < points.size(); ++i){
for (int j = i + 1; j < points.size(); ++j){
for (int k = j + 1; k < points.size(); ++k){
if (checkColor(points[i],points[j],points[k])){
double t_area = count_triangle_area(points[i],points[j],points[k]);
if (t_area == -1){ // 浮点数比较不能直接用==,应该用一个小的范围。这里我图省事了
continue;
}
if (t_area > max_area){
max_area = t_area;
}
}
}
}
}
cout << setiosflags(ios::fixed) << setprecision(5);
cout << max_area << endl;
}
参考:https://blog.csdn.net/hjq376247328/article/details/49465137