Triangle
Time Limit: 3000MS | Memory Limit: 30000K | |
Total Submissions: 7882 | Accepted: 2318 |
Description
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
Source
凸包+ 旋转卡壳
具体做法是枚举三角形的第一个点i,设j = i + 1,k = j + 1。然后做以下操作:
1.计算i,j,k构成的三角形面积a1和i,j,k + 1构成的三角形面积a2,如果a2 < a1,则进行下一步,否则k++,重复此步。
2.记录此时的三角形面积b,如果b < preb(就是上一个j对应的三角形面积)j++,转第一步,否则退出。
1.计算i,j,k构成的三角形面积a1和i,j,k + 1构成的三角形面积a2,如果a2 < a1,则进行下一步,否则k++,重复此步。
2.记录此时的三角形面积b,如果b < preb(就是上一个j对应的三角形面积)j++,转第一步,否则退出。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
struct Point
{
double x,y;
Point (double x=0, double y=0) : x(x),y(y) {}
};
typedef Point Vector;
Vector operator - (Point A, Point B) {return Vector(A.x-B.x , A.y-B.y); }
Point a[55555],p[55555];
int n,m;
bool cmp(const Point &a, const Point &b)
{
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
double Cross( Vector A, Vector B)
{
return A.x*B.y-A.y*B.x;
}
void ConvexHull ()
{
m=0;
sort(p,p+n,cmp);
for (int i=0; i<n; i++)
{
while (m>1 && Cross(a[m-1]-a[m-2], p[i]-a[m-2])<=0 ) m--;
a[m++]=p[i];
}
int k=m;
for (int i=n-2; i>=0; i--)
{
while (m>k && Cross(a[m-1]-a[m-2],p[i]-a[m-2])<=0 ) m--;
a[m++]=p[i];
}
m--;
}
int main()
{
while (1)
{
scanf("%d",&n);
if (n==-1) break;
for (int i=0; i<n; i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
ConvexHull ();
double ans=0;
for (int i=0; i<m; i++)
{
int j=i+1,k=j+1;
if (k>=m) break;
double area,pre=-1.0;
while (j<m-1)
{
area=Cross(a[j]-a[i],a[k]-a[i]);
while ( k+1<m && Cross(a[j]-a[i], a[k+1]-a[i])>area)
{
area=Cross(a[j]-a[i], a[k+1]-a[i]);
k++;
}
if (area<pre) break;
pre=area;
ans=max(ans,area);
j++;
if (j>=k)
{
k=j+1;
if (k>=m) break;
}
}
}
printf("%.2lf\n",ans/2.);
}
return 0;
}