二維凸包模板

來源:互聯網
上載者:User
#include<stdio.h>#include<math.h>#include<algorithm>#include<iostream>using namespace std;const int MAXN=1000;struct point{    int x,y;};point list[MAXN];int stack[MAXN],top;int cross(point p0,point p1,point p2) //計算叉積  p0p1 X p0p2 {    return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);}    double dis(point p1,point p2)  //計算 p1p2的 距離 {    return sqrt((double)(p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y));}    bool cmp(point p1,point p2) //極角排序函數 , 角度相同則距離小的在前面 {    int tmp=cross(list[0],p1,p2);    if(tmp>0) return true;    else if(tmp==0&&dis(list[0],p1)<dis(list[0],p2)) return true;    else return false;}    void init(int n) //輸入,並把  最左下方的點放在 list[0]  。並且進行極角排序 {    int i,k;    point p0;    scanf("%d%d",&list[0].x,&list[0].y);    p0.x=list[0].x;    p0.y=list[0].y;    k=0;    for(i=1;i<n;i++)    {        scanf("%d%d",&list[i].x,&list[i].y);        if( (p0.y>list[i].y) || ((p0.y==list[i].y)&&(p0.x>list[i].x)) )        {            p0.x=list[i].x;            p0.y=list[i].y;            k=i;        }        }        list[k]=list[0];    list[0]=p0;        sort(list+1,list+n,cmp);}     void graham(int n){    int i;    if(n==1) {top=0;stack[0]=0;}    if(n==2)    {        top=1;        stack[0]=0;        stack[1]=1;    }        if(n>2)    {        for(i=0;i<=1;i++) stack[i]=i;        top=1;                for(i=2;i<n;i++)        {            while(top>0&&cross(list[stack[top-1]],list[stack[top]],list[i])<=0) top--;            top++;            stack[top]=i;        }        }    }    

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.