题目大意:给出平面上的一些点,问这些点中的任意三个点组成的三角形的面积和是多少。
思路:看数据范围只算法系列。由于每个三角形有三个顶点,因此暴力的话应该是O(n^3)的时间复杂度,很明显超时了,但是我们只需要将它优化到O(n^2logn)就可以解决了。
好吧,剩下的随便猜一猜,比如O(n^2)的枚举,然后剩下的logn什么也干不了。。。
再比如O(n)的枚举,然后剩下O(nlogn)排序。。。
好像有戏啊。。
枚举每一个点,计算以这个点为坐标原点,在第一象限的所有点与原点组成的三角形的面积和。计算面积可以用叉积,但是这样算和暴力枚举有什么区别?
利用叉积的性质,我们简单的推倒一下。设原点为O,枚举到的两个点为AB,向量OA = (x1,y1),向量OB = (x2,y2),则
S-OAB = |x1 * y2 - y2 * x2|
对于固定的一个点A来说,线段OA与其他所有点的面积和就是ΣS = x1 * Σy2 - y1 * Σx2
但是这需要满足面积不能为负数。只需要按照极角或者斜率排序一下就可以避免负数了。这样正好是O(n^2logn)
CODE:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define INF 0x7f7f7f7f
#define MAX 3010
using namespace std;
struct Point{
int x,y;
double slope;
Point(int _ = 0,int __ = 0):x(_),y(__) {}
bool operator <(const Point &a)const {
if(x == a.x) return y < a.y;
return x < a.x;
}
Point operator -(const Point &a)const {
return Point(x - a.x,y - a.y);
}
void Read() {
scanf("%d%d",&x,&y);
}
}point[MAX],now;
int points;
bool cmp(const Point &a,const Point &b)
{
return a.slope < b.slope;
}
inline long long Calc(int p,int cnt)
{
static Point temp[MAX];
now = point[p];
memcpy(temp + 1,point + p + 1,sizeof(Point) * cnt);
for(int i = 1; i <= cnt; ++i) {
temp[i] = temp[i] - now;
if(!temp[i].x) temp[i].slope = INF;
else temp[i].slope = (double)temp[i].y / (double)temp[i].x;
}
sort(temp + 1,temp + cnt + 1,cmp);
static long long sum_x[MAX],sum_y[MAX],re;
re = 0;
memset(sum_x,0,sizeof(sum_x));
memset(sum_y,0,sizeof(sum_y));
for(int i = cnt; i; --i) {
sum_x[i] = sum_x[i + 1] + temp[i].x;
sum_y[i] = sum_y[i + 1] + temp[i].y;
}
for(int i = 1; i < cnt; ++i) {
re += temp[i].x * sum_y[i + 1];
re -= temp[i].y * sum_x[i + 1];
}
return re;
}
int main()
{
cin >> points;
for(int i = 1; i <= points; ++i)
point[i].Read();
sort(point + 1,point + points + 1);
long long ans = 0;
for(int i = 1; i <= points; ++i)
ans += Calc(i,points - i);
bool flag = ans&1;
printf("%lld.%d\n",ans >> 1,(int)flag ? 5:0);
return 0;
}