题意:
给平面上n个点,求这n个点组成的最大三角形面积。
分析:
旋转卡壳,但要注意和求平面最远点对的区别,最大三角形的边不一定在凸包上的,也贴出以前写的求平面最远点对的poj 2187代码作为对比。
代码:
//poj 2079
//sep9
#include <iostream>
#include <algorithm>
using namespace std;
const int maxN=50012;
struct P
{
int x,y;
}pnt[maxN],cnt[maxN];
int n;
int cmp(P a,P b)
{
if(a.y!=b.y)
return a.y<b.y;
return a.x<b.x;
}
int cross(P a,P b,P c)
{
int x1=b.x-a.x;
int y1=b.y-a.y;
int x2=c.x-a.x;
int y2=c.y-a.y;
return x1*y2-x2*y1;
}
int graham()
{
sort(pnt,pnt+n,cmp);
int i,pos=1;
cnt[0]=pnt[0];
cnt[1]=pnt[1];
for(i=2;i<n;++i){
while(pos>0&&cross(cnt[pos-1],cnt[pos],pnt[i])<=0) --pos;
cnt[++pos]=pnt[i];
}
int bak=pos;
for(i=n-2;i>=0;--i){
while(pos>bak&&cross(cnt[pos-1],cnt[pos],pnt[i])<=0) --pos;
cnt[++pos]=pnt[i];
}
return pos;
}
int main()
{
while(scanf("%d",&n)==1&&n!=-1){
for(int i=0;i<n;++i)
scanf("%d%d",&pnt[i].x,&pnt[i].y);
int pos=graham();
int ans=0,p=1,i,j,k;
for(i=j=k=0;i<pos;++i){
while(abs(cross(cnt[i],cnt[j],cnt[(k+1)%pos]))>abs(cross(cnt[i],cnt[j],cnt[k])))
k=(k+1)%pos;
while(abs(cross(cnt[i],cnt[(j+1)%pos],cnt[k]))>abs(cross(cnt[i],cnt[j],cnt[k])))
j=(j+1)%pos;
ans=max(ans,abs(cross(cnt[i],cnt[j],cnt[k])));
}
printf("%.2lf\n",ans/2.0);
}
return 0;
}
求最远点对的代码:
//poj 2187
//sep9
#include<iostream>
#include<algorithm>
using namespace std;
struct Point
{
int x,y;
}points[50012],bag[50012];
int cross(Point p1,Point p2,Point p0)
{
return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);
}
int cmp(Point a,Point b)
{
return a.y==b.y?a.x<b.x:a.y<b.y;
}
int dis(Point a,Point b)
{
return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
int getBag(Point p[],int n,Point bag[])
{
int i,bp=1;
bag[0]=p[0];
bag[1]=p[1];
for(i=2;i<n;++i)
{
while(bp&&cross(bag[bp-1],p[i],bag[bp])<=0)
--bp;
bag[++bp]=p[i];
}
int len=bp;
bag[++bp]=p[n-2];
for(i=n-3;i>=0;--i)
{
while(bp>len&&cross(bag[bp-1],p[i],bag[bp])<=0)
--bp;
bag[++bp]=p[i];
}
return bp;
}
int main()
{
int p,i,n;
while(scanf("%d",&n)==1)
{
for(i=0;i<n;++i)
scanf("%d%d",&points[i].x,&points[i].y);
sort(points,points+n,cmp);
int dif,ans=0,m=getBag(points,n,bag);
p=1;
for(i=0;i<m;++i)
{
while(abs(cross(bag[i],bag[i+1],bag[p+1]))>abs(cross(bag[i],bag[i+1],bag[p])))
p=(p+1)%m;
ans=max(ans,max(dis(bag[i],bag[p]),dis(bag[i+1],bag[p+1])));
}
printf("%d\n",ans);
}
}