计算几何的题。
最近在准备其中考试,刚刚有空做一题。。
这题我判断点是否在三角形内,用的是比较面积的方法:三角形的面积 和 三个测试点与三角形其他两点组成三角形面积和 判等;
面积使用叉积得出;
#include <iostream>
#include <cmath>
using namespace std;
typedef struct{
double x, y;
}point;
double cross(point &start, point &basic, point &target)
{
return (basic.x - start.x)*(target.y - start.y) - (basic.y - start.y)*(target.x - start.x);
}
char label[15] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'
};
int N;
point points[15];
double area(point &p1, point &p2, point &p3)
{
return abs((p2.x - p1.x)*(p3.y - p1.y) - (p2.y - p1.y)*(p3.x - p1.x));
}
bool test(int i, int j, int k, double tarea)
{
for(int t = 0; t < N; t++){
if(t == i || t == j || t == k)
continue;
double x = area(points[t], points[i], points[j]);
x += area(points[t], points[i], points[k]);
x += area(points[t], points[k], points[j]);
if(abs(x - tarea) < 1E-7)
return false;
}
return true;
}
int main()
{
while(cin >> N){
if(!N) break;
double maxarea = 0;
char temp;
for(int i = 0; i < N; i++){
cin >> temp >> points[i].x >> points[i].y;
}
char answer[3];
for(int i = 0; i < N; i++)
for(int j = i+1; j < N; j++)
for(int k = j+1; k < N; k++){
double narea = area(points[i], points[j], points[k]);
if(!test(i, j, k, narea)) continue;
if(narea > maxarea){
answer[0] = label[i];
answer[1] = label[j];
answer[2] = label[k];
maxarea = narea;
}
}
cout << answer[0] << answer[1] << answer[2] << endl;
}
}