凸包上的点(共12个点)并输出部分点的c++代码实现
时间: 2024-09-13 19:16:32 浏览: 40
C++OpenCV3源代码寻找和绘制物体的凸包
凸包是指在一个点集中,所有的点都在凸包的边界上或内部的一个最小凸多边形。最常见的算法来计算二维点集的凸包是Graham扫描算法和Jarvis步进算法(也称为gift wrapping算法)。这里我将提供一个简化的Graham扫描算法实现部分点凸包的C++代码示例。
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
struct Point {
int x, y;
};
int orientation(Point p, Point q, Point r) {
int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clock or counterclock wise
}
bool compare(Point p1, Point p2, Point q) {
int o = orientation(q, p1, p2);
if (o == 0)
return (dist(q, p1) >= dist(q, p2));
return (o == 1);
}
void convexHull(vector<Point> &points, int n) {
int ymin = points[0].y, min = 0;
for (int i = 1; i < n; i++) {
int y = points[i].y;
if ((y < ymin) || (ymin == y && points[i].x < points[min].x))
ymin = points[i].y, min = i;
}
int p = min, q;
do {
q = (p + 1) % n;
for (int i = 0; i < n; i++) {
if (orientation(points[min], points[i], points[q]) == 2)
q = i;
}
swap(points[min], points[q]);
p = min;
min = q;
} while (min != 0);
int m = 0;
for (int i = 1; i < n; i++) {
if (orientation(points[0], points[i], points[m]) == 2)
m = i;
}
swap(points[0], points[m]);
sort(points.begin(), points.end(), [points](Point p1, Point p2) {
return compare(p1, p2, points[0]);
});
vector<Point> hull;
for (int i = 0; i <= m; i++) {
while (hull.size() >= 2 && orientation(hull[hull.size()-2], hull[hull.size()-1], points[i]) != 2)
hull.pop_back();
hull.push_back(points[i]);
}
for (int i = m - 1; i >= 0; i--) {
while (hull.size() >= 2 && orientation(hull[hull.size()-2], hull[hull.size()-1], points[i]) != 2)
hull.pop_back();
hull.push_back(points[i]);
}
// 输出凸包上的部分点
for (int i = 0; i < hull.size(); i++) {
cout << "(" << hull[i].x << ", " << hull[i].y << ")" << endl;
}
}
int main() {
vector<Point> points = {{0, 3}, {1, 1}, {2, 2}, {4, 4},
{0, 0}, {1, 2}, {3, 1}, {3, 3}};
int n = points.size();
convexHull(points, n);
return 0;
}
```
上述代码中,我们首先找到纵坐标最小的点作为起始点,然后按照顺时针方向对所有点进行排序。之后使用Graham扫描算法找到凸包的顶点。最终我们输出构成凸包的点。
阅读全文