程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVa 10256 The Great Divide,判斷兩個凸包是否相離

UVa 10256 The Great Divide,判斷兩個凸包是否相離

編輯:C++入門知識

UVa 10256 The Great Divide,判斷兩個凸包是否相離



先從給出的兩個點集中分別計算出兩個凸包,

然後判斷兩個凸包是否相離。


#include
#include
#include
#include
using namespace std;

const double eps = 1e-10;
double dcmp(double x) {
    if(fabs(x) < eps) return 0;
    else return x < 0 ? -1 : 1;
}

struct Point {
    double x, y;
    Point(double x=0, double y=0):x(x),y(y) {}
};

typedef Point Vector;

Vector operator - (const Point& A, const Point& B) {
    return Vector(A.x-B.x, A.y-B.y);
}

double Cross(const Vector& A, const Vector& B) {
    return A.x*B.y - A.y*B.x;
}

double Dot(const Vector& A, const Vector& B) {
    return A.x*B.x + A.y*B.y;
}

bool operator < (const Point& p1, const Point& p2) {
    return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y);
}

bool operator == (const Point& p1, const Point& p2) {
    return p1.x == p2.x && p1.y == p2.y;
}

bool SegmentProperIntersection(const Point& a1, const Point& a2, const Point& b1, const Point& b2) {
    double c1 = Cross(a2-a1,b1-a1), c2 = Cross(a2-a1,b2-a1),
           c3 = Cross(b2-b1,a1-b1), c4=Cross(b2-b1,a2-b1);
    return dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0;
}

bool OnSegment(const Point& p, const Point& a1, const Point& a2) {
    return dcmp(Cross(a1-p, a2-p)) == 0 && dcmp(Dot(a1-p, a2-p)) < 0;
}

// 點集凸包
// 如果不希望在凸包的邊上有輸入點,把兩個 <= 改成 <
// 如果不介意點集被修改,可以改成傳遞引用
vector ConvexHull(vector p) {
    // 預處理,刪除重復點
    sort(p.begin(), p.end());
    p.erase(unique(p.begin(), p.end()), p.end());

    int n = p.size();
    int m = 0;
    vector ch(n+1);
    for(int i = 0; i < n; i++) {
        while(m > 1 && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
        ch[m++] = p[i];
    }
    int k = m;
    for(int i = n-2; i >= 0; i--) {
        while(m > k && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
        ch[m++] = p[i];
    }
    if(n > 1) m--;
    ch.resize(m);
    return ch;
}

int IsPointInPolygon(const Point& p, const vector& poly) {
    int wn = 0;
    int n = poly.size();
    for(int i=0; i 0 && d1 <= 0 && d2 > 0) wn++;
        if(k < 0 && d2 <= 0 && d1 > 0) wn--;
    }
    if(wn != 0) return 1;
    return 0;
}


bool ConvexPolygonDisjoint(const vector ch1, const vector ch2) {
    int c1 = ch1.size();
    int c2 = ch2.size();
    for(int i=0; i 0 && m > 0) {
        vector P1, P2;
        double x, y;
        for(int i = 0; i < n; i++) {
            scanf("%lf%lf", &x, &y);
            P1.push_back(Point(x, y));
        }
        for(int i = 0; i < m; i++) {
            scanf("%lf%lf", &x, &y);
            P2.push_back(Point(x, y));
        }
        if(ConvexPolygonDisjoint(ConvexHull(P1), ConvexHull(P2)))
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved