1. 程式人生 > >Triangle (旋轉卡殼求最大三角形面積)

Triangle (旋轉卡殼求最大三角形面積)

Given n distinct points on a plane, your task is to find the triangle that have the maximum area, whose vertices are from the given points.

Input

The input consists of several test cases. The first line of each test case contains an integer n, indicating the number of points on the plane. Each of the following n lines contains two integer xi and yi, indicating the ith points. The last line of the input is an integer −1, indicating the end of input, which should not be processed. You may assume that 1 <= n <= 50000 and −10 4 <= xi, yi <= 10 4 for all i = 1 . . . n.

Output

For each test case, print a line containing the maximum area, which contains two digits after the decimal point. You may assume that there is always an answer which is greater than zero.

Sample Input

3
3 4
2 6
2 7
5
2 6
3 9
2 0
8 0
6 5
-1

Sample Output

0.50
27.00

題意:

在二維平面上有n個點,每個的座標已知,求能夠成三角形的最大面積

思路:

找到包含這些點的最大凸包,最大三角形的三個頂點一定在凸包上,旋轉卡殼求最大面積

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 50005;
struct Point{
	int x,y;
	Point(){
	}
	Point(int xx,int yy){
		x=xx;
		y=yy;
	}
}p[N];
Point operator-(const Point a,const Point b){
	return Point(a.x-b.x,a.y-b.y);
} 
int operator*(const Point a,const Point b){
	return a.x*b.y-a.y*b.x;
}
int cross(Point a,Point b,Point c){  //叉積 
	return (b-a)*(c-a);
}
int dis(Point a,Point b){
	int X=(a.x-b.x)*(a.x-b.x);
	int Y=(a.y-b.y)*(a.y-b.y);
    return X+Y;
}
bool judge(Point a,Point b){
	if(a.y==b.y) return a.x<b.x;
	return a.y<b.y;
}
bool cmp(Point b,Point c){  //極角排序 
	Point a=p[0];
	int ans=cross(a,b,c);
	if(ans==0) return dis(a,b)<dis(a,c);
	return ans>0;
}
int n,top,sta[N];
void solve(){  //求解最大凸包 
	int t=0;
	for(int i=1;i<n;i++)
	   if(judge(p[i],p[t])) t=i;
	swap(p[0],p[t]);
	sort(p+1,p+n,cmp);
	sta[0]=0;
	sta[1]=1;
	top=1;
	for(int i=2;i<n;i++){
		while(top&&cross(p[sta[top-1]],p[sta[top]],p[i])<0) top--;
		sta[++top]=i;
	}
	top++;
}
void RC(){   //旋轉卡殼求最大三角面積 
	int ans=0;
	for(int i=0;i<top;i++){
		int down=(i+1)%top;
		int up=(down+1)%top;
		while(up!=i&&down!=i){
			ans=max(ans,abs(cross(p[sta[i]],p[sta[down]],p[sta[up]])));
//			printf("down:%d  up:%d ans:%d\n",sta[down],sta[up],ans);
			while(abs(cross(p[sta[i]],p[sta[down]],p[sta[up]]))<abs(cross(p[sta[i]],p[sta[down]],p[sta[(up+1)%top]])))
			up=(up+1)%top;
			down=(down+1)%top;
		}
	}
	printf("%.2f\n",0.5*ans);
}
int main(){
	while(~scanf("%d",&n)&&n!=-1){
		for(int i=0;i<n;i++){
			scanf("%d%d",&p[i].x,&p[i].y);
		}
		solve();
//		printf("top: %d\n",top);
		RC();
//        for(int i=0;i<top;i++)
//           printf("(%d,%d)\n",p[sta[i]].x,p[sta[i]].y);
	}
	return 0;
}