2 4 0 0 1 0 0 1 1 1 2 0 0 0 1
1.0 0.0
题意是说给定一些点求包含这些点的最小凸边形面积,直接套用模板做的。。。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;
#define MAX 100002
#define eps 1e-9
int n,cnt;
struct Point
{
double x,y;
Point (){}
Point ( double x, double y ) : x(x) , y(y) {}
}p[MAX],ch[MAX];
typedef Point Vector;
Point operator - ( Point a , Point b ) { return Point ( a.x - b.x , a.y - b.y ); }
bool cmp ( Point a , Point b ) //将每个点通过优先x最小然后y最小的顺序来排序
{
if ( a.x != b.x ) return a.x < b.x;
else return a.y < b.y;
}
int dcmp ( double x )
{
if ( fabs ( x ) < eps ) return 0;
else return x < 0 ? -1 : 1;
}
double Cross ( Vector u , Vector v ) //叉乘
{
return u.x * v.y - u.y * v.x;
}
int ConvexHull ( Point *p , Point *ch ) //求凸包Andrew算法
{
sort ( p , p + n , cmp );
int m = 0;
for ( int i = 0 ; i < n ; i ++ )
{
while ( m > 1 && dcmp ( Cross ( ch[m-1] - ch[m-2] , p[i] - ch[m-2] ) ) <= 0 ) m--;
ch[m++] = p[i];
}
int k = m;
for ( int i = n - 2 ; i >= 0 ; i -- )
{
while ( m > k && dcmp ( Cross ( ch[m-1] - ch[m-2] , p[i] - ch[m-2] ) ) <= 0 ) m --;
ch[m++] = p[i];
}
return m;
}
double PolygonArea ( Point *ch ) //求多边形面积(因为是凸包所以它的有向面积就是它本身的面积
{
double area = 0;
for ( int i = 1 ; i < cnt -1 ; i ++ )
{
area += Cross ( ch[i] - ch[0] , ch[i+1] - ch[0] );
//cout << area << endl;
}
return area / 2.0;
}
int main()
{
int t;
scanf("%d",&t);
while ( t-- ){
scanf ( "%d" , &n );
for( int i = 0 ; i < n ; i ++ )
scanf ( "%lf%lf" , &p[i].x , &p[i].y );
cnt = ConvexHull ( p , ch );
printf ( "%.1lf\n" , PolygonArea( ch ) );
}
return 0;
}
原文地址:http://blog.csdn.net/u012773338/article/details/38273225