凸包算法

ThirdConvexHull.h

#pragma once
class CThirdConvexHull
{
public:
CThirdConvexHull();
~CThirdConvexHull();

public:
static AcGePoint3dArray testConvexHullPoints(AcGePoint3dArray& pts);
};

 

ThirdConvexHull.cpp

#include "stdafx.h"
#include "ThirdConvexHull.h"

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
using std::sort;
#define MAXN 1002
int N, L;
double sqr(double a)
{
return a*a;
}
struct Point
{
double x, y;
inline Point operator- (const Point &t)
{
Point ret;
ret.x = x - t.x;
ret.y = y - t.y;
return ret;
}
inline Point operator+ (const Point &t)
{
Point ret;
ret.x = x + t.x;
ret.y = y + t.y;
return ret;
}
inline int det(const Point &t)
{
return x*t.y - t.x*y;
}
inline double dist(Point &t)
{
return sqrt(sqr(x - t.x) + sqr(y - t.y));
}
}d[MAXN];
bool cmpPoint(const Point &a, const Point &b)
{
if (a.x != b.x) return a.x < b.x;
return a.y < b.y;
}
int convex[MAXN], cTotal;
void get_convex_hull()
{
sort(d, d + N, cmpPoint);
int Total = 0, tmp;
for (int i = 0; i < N; ++i)
{
while ((Total > 1) &&
((d[convex[Total - 1]] - d[convex[Total - 2]]).det(
d[i] - d[convex[Total - 1]]) <= 0)) Total--;
convex[Total++] = i;
}
tmp = Total;
for (int i = N - 2; i >= 0; --i)
{
while ((Total > tmp) &&
((d[convex[Total - 1]] - d[convex[Total - 2]]).det(
d[i] - d[convex[Total - 1]]) <= 0)) Total--;
convex[Total++] = i;
}
cTotal = Total;
}

CThirdConvexHull::CThirdConvexHull()
{
}


CThirdConvexHull::~CThirdConvexHull()
{
}

AcGePoint3dArray CThirdConvexHull::testConvexHullPoints(AcGePoint3dArray& pts)
{

AcGePoint3dArray outpts;

N = pts.length();
for (int i = 0; i < N; ++i)
{
d[i].x = pts[i].x;
d[i].y = pts[i].y;
}
get_convex_hull();
double Ans = 0;
for (int i = 0; i < cTotal; ++i)
{
AcGePoint3d tempt;
tempt.x = d[convex[i]].x;
tempt.y = d[convex[i]].y;
tempt.z = 0;
outpts.append(tempt);
//acutPrintf(_T("\n%2f,%2f,0"), d[convex[i]].x, d[convex[i]].y);
}
return outpts;
}

posted @ 2020-03-09 09:57  久龄  阅读(35)  评论(0编辑  收藏  举报