這個題目給定平面一些點的集合,要求你求出多有三角形中最大的一個,這個題目一般沒有接觸過計算幾何的人一開始想到的一定是枚舉
對的,想的沒錯就是枚舉,不過這裡的枚舉不是就在原來的點的集合裡面枚舉,我們要進行一些處理,這個處理就是求出凸包,然後按照
凸包上出現點的順序來枚舉,這樣速度就上來了,想想也知道,擁有最大三角形的三個點一定都會在凸包上面,這樣就減少枚舉不必要的
點
#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>#include <cmath>using namespace std;#define eps 1e-6#define PI 3.14159265struct point{double x;double y;}po[100000],temp;int n,pos;bool zero(double a){return fabs(a) < eps;}double dis(point &a,point &b)//返回兩點之間距離的平方{return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);}double across(point &a,point &b,point &c)//求a b and a c 的X積{return (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);}int cmp(const void *a,const void *b){return across(po[0],*(point*)a,*(point*)b) > 1e-8 ? -1 : 1;}int select(){int i,j,k=1;for(i=2;i<n;i++){if(zero(across(po[0],po[k],po[i]))){if(dis(po[0],po[k]) < dis(po[0],po[i]))po[k]=po[i];}elsepo[++k]=po[i];}return k+1;}int graham(int num){int i,j,k=2;//////////////////////////////////////////po[num]=po[0];//fangbiannum++;for(i=3;i<num;i++){while(across(po[k-1],po[k],po[i]) < -eps){k--;}po[++k]=po[i];//就這個迴圈結束,不需要了!}/*for(i=0;i<k;i++)printf("%lf %lf\n",po[i].x,po[i].y);printf("\n");*/return k;}double cal_max_area(int num){ int i,j,k; double ans,temp; ans=-1; for(i=0;i<num;i++) for(j=i+1;j<num;j++) for(k=j+1;k<num;k++) { temp=across(po[i],po[j],po[k]); if(ans < temp) ans=temp; } return ans;}int main(){int i,j,k,num;point my_temp;while(scanf("%d",&n)!=EOF){scanf("%lf%lf",&po[0].x,&po[0].y);temp=po[0];pos=0;for(i=1;i<n;i++){scanf("%lf%lf",&po[i].x,&po[i].y);if(po[i].y < temp.y)temp=po[i],pos=i;}my_temp=po[0];po[0]=po[pos];po[pos]=my_temp;qsort(po+1,n-1,sizeof(po[0]),cmp);num=graham(select());printf("%.2lf\n",cal_max_area(num)/2);}return 0;}