溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++算法庫(kù)中的凸包算法實(shí)現(xiàn)

發(fā)布時(shí)間:2024-08-13 12:53:29 來源:億速云 閱讀:100 作者:小樊 欄目:編程語(yǔ)言

C++算法庫(kù)中常用的凸包算法實(shí)現(xiàn)是Graham Scan算法。以下是一個(gè)簡(jiǎn)單的實(shí)現(xiàn)示例:

#include <iostream>
#include <vector>
#include <algorithm>

struct Point {
    int x, y;
};

// 用于比較兩個(gè)點(diǎn)的極角
bool compare(Point a, Point b) {
    return a.x < b.x || (a.x == b.x && a.y < b.y);
}

// 計(jì)算兩點(diǎn)之間的叉積
int crossProduct(Point a, Point b, Point c) {
    return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}

// Graham Scan算法
std::vector<Point> convexHull(std::vector<Point>& points) {
    int n = points.size();
    if (n < 3) {
        return points;
    }

    std::sort(points.begin(), points.end(), compare);

    std::vector<Point> hull;
    // 下凸殼
    for (int i = 0; i < n; i++) {
        while (hull.size() >= 2 && crossProduct(hull[hull.size() - 2], hull.back(), points[i]) <= 0) {
            hull.pop_back();
        }
        hull.push_back(points[i]);
    }
    // 上凸殼
    int t = hull.size() + 1;
    for (int i = n - 2; i >= 0; i--) {
        while (hull.size() >= t && crossProduct(hull[hull.size() - 2], hull.back(), points[i]) <= 0) {
            hull.pop_back();
        }
        hull.push_back(points[i]);
    }

    hull.pop_back(); // 移除重復(fù)的起始點(diǎn)
    return hull;
}

int main() {
    std::vector<Point> points = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};
    std::vector<Point> hull = convexHull(points);

    std::cout << "Convex Hull Points:\n";
    for (Point p : hull) {
        std::cout << "(" << p.x << ", " << p.y << ")\n";
    }

    return 0;
}

在這個(gè)示例中,我們首先定義了一個(gè)Point結(jié)構(gòu)體用于表示二維點(diǎn)的坐標(biāo)。然后實(shí)現(xiàn)了比較兩個(gè)點(diǎn)的極角的比較函數(shù)compare和計(jì)算兩點(diǎn)之間的叉積的函數(shù)crossProduct。最后實(shí)現(xiàn)了Graham Scan算法函數(shù)convexHull來計(jì)算凸包。

main函數(shù)中,我們定義了一些二維點(diǎn),并調(diào)用convexHull函數(shù)來計(jì)算凸包,并輸出凸包的點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI