【问题描述】
给定二维的平面上n个不同的点,要求在这些点里寻找三个点,使他们构成的三角形拥有的面积最大。
我是在问答上看到的这个问题--出构成的最大的三角形的面积,结果保留两位小数。C语言,谢谢
【分析】
主要的过程在于如何求出所有的排列组合情况:
这里需要用到回溯法求解。
其他的就比较好办了
代码:
#include <stdio.h>
#include <math.h>
#define MAX 100
int b[2][MAX], a[MAX], x, y, z, c[MAX], d[3][MAX];
double Area[MAX];
double area(double a, double b, double c)
{
double p = (a + b + c) / 2;
return sqrt(p*(p - a)*(p - b)*(p - c));
}
void comb(int n, int r)
{
int i, j,*p;
p = &c[0];
i = 0;
a[i] = 1;
do
{
if (a[i] - i <= n - r + 1)
{
if (i == r - 1)
{
for (j = 0; j < r; j++)
{
//printf("%4d", a[j]);
*p = a[j];
p++;
}
//printf("\n");
a[i]++;
continue;
}
i++;
a[i] = a[i - 1] + 1;
}
else
{
if (i == 0)
return;
a[--i]++;
}
} while (1);
}
double cptlen(int x1,int y1,int x2,int y2)
{
double len = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
return len;
}
void main()
{
printf("输入一个大于等于3的数:\n");
int num, tem_a, tem_b;
scanf("%d", &num);
//getchar();
for (int i = 0; i < num; i++)
{
scanf("%d%d", &tem_a,&tem_b);
getchar();
b[0][i] = tem_a;
b[1][i] = tem_b;
}
comb(num, 3);
//for (int j = 0; j < num;j++)
//{
// printf("%d,%d\n", b[0][j], b[1][j]);
//}
//for (int j = 0; j < sizeof(c)&&c[j]!=0; j++)
//{
//
// printf("%d\n", c[j]);
//
//}
double *q;
q = &Area[0];
for (int j = 0; j < sizeof(c) && c[j+2] != 0; j=j+3)
{
//printf("%d,%d,%d\n", c[j], c[j+1], c[j+2]);
int x1, y1, x2, y2, x3, y3;
x1 = b[0][c[j]-1];
y1 = b[1][c[j]-1];
x2 = b[0][c[j + 1]-1];
y2 = b[1][c[j + 1]-1];
x3 = b[0][c[j + 2]-1];
y3 = b[1][c[j + 2]-1];
double a, b, c;
a = cptlen(x1, y1, x2, y2);
b = cptlen(x2, y2, x3, y3);
c = cptlen(x1, y1, x3, y3);
*q = area(a,b,c);
q++;
}
double area_max = 0;
for (int i = 0; i < sizeof(Area)&&Area[i]!=0;i++)
{
if (Area[i]>area_max)
{
area_max = Area[i];
}
}
printf("%0.2f",area_max);
getchar();
}
测试结果: