首页 > 代码库 > 凸包问题

凸包问题

#include<iostream>
using namespace std;
#define MAXN 1000000
int a[MAXN],b[MAXN]; //点的横纵坐标

void TuBao(int x[MAXN],int y[MAXN],int n)
{
    int count1=0,count2=0;
    for(int i=0;i<=n-2;i++)
    {
        for(int j=i+1;j<=n-1;j++)
        {
            //取得当前的点:(x[i],y[i])和(x[j],y[j])
            int a=y[j]-y[i];
            int b=x[i]-x[j];
            int c=x[i]*y[j]-x[j]*y[i];
            for(int k=0;k<=n-1;k++)
            {
                if(a*x[k]+b*y[k]>=c)
                    count1++;
                if(a*x[k]+b*y[k]<=c)
                    count2++;
            }
            if(count1==n||count2==n) //点(x[i],y[i])和(x[j],y[j])的连线为该集合凸包边界的一部分
                cout<<"("<<x[i]<<","<<y[i]<<")-"<<"("<<x[j]<<","<<y[j]<<")"<<" ";  
            count1=0;
            count2=0;
        }
    }
    cout<<endl;
}

int main()
{
    int n;   
    cout<<"输入点的个数: "<<endl;
    cin>>n;

    for(int i=0;i<n;i++)
    {
        int q=i+1;  
        cout<<"输入第"<<q<<"个点的坐标:";
        cin>>a[i]>>b[i];
        cout<<"("<<a[i]<<","<<b[i]<<")"<<endl;  
    }
    cout<<"得到的结果为:"<<endl;
    TuBao(a,b,n);

    return 0;
}