欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

计算几何学

程序员文章站 2022-02-05 19:26:41
...

计算几何学基础知识,以及基础问题讲解链接

http://dev.gameres.com/Program/Abstract/Geometry.htm#%C5%D0%B6%CF%C1%BD%CF%DF%B6%CE%CA%C7%B7%F1%CF%E0%BD%BB

凸包实现代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <stack>
using namespace std;
#define MaxNode 1015
int Stack[MaxNode];
int top;
typedef struct POINT
{
    double x;
    double y;
}POINT;
POINT point[MaxNode];
void swap(POINT point[],int i,int j)
{
    POINT tmp;
    tmp=point[i];
    point[i]=point[j];
    point[j]=tmp;
}
double multi(POINT p1,POINT p2,POINT p0) //叉乘
{
    return ((p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x));
}
double distence(POINT p1,POINT p2) //p1,p2的距离
{
    return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
int cmp(const void *a,const void *b)
{
    POINT *c=(POINT *)a;
    POINT *d=(POINT *)b;
    double k=multi(*c,*d,point[0]);
    if(k<0) return 1;
    else if(k==0&&distence(*c,point[0])>=distence(*d,point[0])) return 1; //极角相同,比距离
    else return -1;
}
void grahamscan(int n)
{
    int i,u;
    u=0;
    for(i = 1;i<= n-1;i++) //找到最左下的点p0
        if((point[i].y < point[u].y)||(point[i].y==point[u].y&&point[i].x < point[u].x))
            u=i;
    swap(point,0,u);
    qsort(point+1,n-1,sizeof(point[0]),cmp); //按极角排序
    for(i = 0;i <= 2;i++) Stack[i] = i; //p0,p1,p2入栈
    top=2;
    for(i = 3;i <= n-1;i++) //最终凸包的各顶点的编号依次存在stack[]中。
    {
        while(multi(point[i],point[Stack[top]],point[Stack[top-1]])>=0) //弹出非左转的点
        {
            if(top==0)break;
            top--;
        }
        top++;
        Stack[top] = i;
    }
}
//求凸包的面积
double polygonArea(int n,POINT p[])
{
    double area;
    int i;
    area = 0;
    for(i = 1;i <= n;i++){
        area += (p[Stack[i - 1]].x * p[Stack[i % n]].y - p[Stack[i % n]].x * p[Stack[i - 1]].y);
    }
    return fabs(area) / 2;
}
double polygonLength(){
    double ans = 0;
    for(int i = 0;i < top; i++){
        ans += distence(point[Stack[i]], point[Stack[i + 1]]);
    }
    ans += distence(point[Stack[top]], point[Stack[0]]);
    return ans;
}
int main()
{
    int n,d;
    while(cin >> n >> d){
        memset(point, 0, sizeof(point));
        memset(Stack, 0, sizeof(Stack));
        for(int i = 0;i < n;i++){
            cin >> point[i].x >> point[i].y;
        }
        grahamscan(n);
    }
}

判断线段是否相交(代码)

typedef struct point
{
    double x;
    double y;
}point;
typedef struct stick{
    point begin;
    point end;
    int flag;
}stick;
double multi(point p1,point p2,point p0) //叉乘
{
    return ((p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x));
}
int cross(stick a,stick b){//是否相交,相交返回1,不相交返回0,点在线上也算相交
    if(multi(a.begin,b.end,b.begin) * multi(a.end,b.end,b.begin) > 0 || multi(b.begin, a.end, a.begin) * multi(b.end, a.end, a.begin) > 0){
        return 0;
    }
    else
        return 1;
}

持续更新

相关标签: 计算几何学