【算法】一些牛逼轰轰的算法记录

1.判断点是否在三角形内

衍生:快速计算三角形面积

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <string>
#include <math.h>
#define S_FLOAT 0.00000001

using namespace std;
//点类型
typedef struct Point
{
float x;
float y;
Point() {}
Point(float x,float y)
{
this->x = x;
this->y = y;
}
};
//计算三角形面积
float GetTriangleSquar(const Point a, const Point b, const Point c)
{
Point AB, BC;
AB.x = b.x - a.x;
AB.y = b.y - a.y;
BC.x = c.x - b.x;
BC.y = c.y - b.y;
return fabs(AB.x*BC.y - AB.y*BC.x) / 2;
}
//判断点是否在三角形内
string IsInTriang(Point a, Point b, Point c, Point d)
{
float Sabc, Sabd, Sacd, Sbcd;
Sabc = GetTriangleSquar(a, b, c);
Sabd = GetTriangleSquar(a, b, d);
Sacd = GetTriangleSquar(a, c, d);
Sbcd = GetTriangleSquar(b, c, d);
float Sums = Sabd + Sacd + Sbcd;
cout << "Sabd:" << Sabd << endl << "Sacd:" << Sacd << endl << "Sbcd:" << Sbcd << endl;
cout<< "Sabc:"<<Sabc<<endl<<"Sums:"<<Sums << endl;
if ((-S_FLOAT < (Sabc - Sums) && (Sabc - Sums) < S_FLOAT))
return "Yes";
else return "No";
}
//测试函数
void Test()
{
Point a(2, 2), b(0, 0), c(4, 0), d(2, 1);
cout << IsInTriang(a, b, c, d) << endl;
}
int main()
{
Test();
system("pause");
return 0;
}

2.PNPoly算法-判断点是否在多边形内

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool PointInPolygon(Point point, Polygon polygon) {
vector<Point> points = polygon.getPoints();
int i, j, nvert = points.size();
bool c = false;

for(i = 0, j = nvert - 1; i < nvert; j = i++) {
if( ( (points[i].y >= point.y ) != (points[j].y >= point.y) ) &&
(point.x <= (points[j].x - points[i].x) * (point.y - points[i].y) / (points[j].y - points[i].y) + points[i].x)
)
c = !c;
}

return c;
}