POJ 3348 Cows (凸包面积)

http://poj.org/problem?id=3348


水。


完整代码:

/*0ms,680KB*/

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const double eps = 1e-8;
const int mx = 10005;

struct point
{
	double x, y;
	point(double x = 0.0, double y = 0.0): x(x), y(y) {}
	void read() const
	{
		scanf("%lf%lf", &x, &y);
	}
	bool operator == (const point& a) const
	{
		return fabs(x - a.x) < eps && fabs(y - a.y) < eps;
	}
	bool operator < (const point& a) const
	{
		return x < a.x || fabs(x - a.x) < eps && y < a.y;
	}
};

point a[mx], ans[mx];
int n, len;

///oa x ob
inline double cross_product(point& a, point& b)
{
	return a.x * b.y - a.y * b.x;
}

///ab x ac
inline double cross_product(point& a, point& b, point& c)
{
	return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}

///求凸包
void convex_hull()
{
	sort(a, a + n);
	//unique(a, a + n);
	len = 0;
	int i;
	for (i = 0; i < n; ++i)
	{
		while (len >= 2 && cross_product(ans[len - 2], ans[len - 1], a[i]) < eps)
			--len;
		ans[len++] = a[i];
	}
	int tmp = len;
	for (i = n - 2; i >= 0; --i)
	{
		while (len > tmp && cross_product(ans[len - 2], ans[len - 1], a[i]) < eps)
			--len;
		ans[len++] = a[i];
	}
	--len;
}

///求多边形面积 的两倍 。以原点为向量起点。注意ans[]要是顺时针顺序
double area()
{
	double sum = 0.0;
	ans[len] = ans[0];
	for (int i = 0; i < len; ++i) sum += cross_product(ans[i], ans[i + 1]);
	return sum;
}

int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; ++i) a[i].read();
	if (n < 3) puts("0");
	else
	{
		convex_hull();
		printf("%d\n", (int)(area() / 100.0));
	}
	return 0;
}

你可能感兴趣的:(C++,ACM,poj,凸包)