题意
给出
n
n
n 个点,第
i
i
i 个点的坐标为
(
x
i
,
y
i
)
(x_i,y_i)
(xi,yi)。求可以形成的严格凸四边形个数。
其中,
1
≤
n
≤
700
1\le n\le 700
1≤n≤700。
分析
纪念自己独立写出来的第一道计算几何!!
考虑 答案
=
C
n
4
−
=C_n^4-
=Cn4− 凹四边形的个数。
凹四边形意味着有一个点在另外三个点围成的三角形内部(包括边界)。
因此我们枚举在内部的点
A
A
A,然后用
C
n
−
1
3
C_{n-1}^3
Cn−13 减去不包含
A
A
A 的三角形个数。然后对于剩下的点,枚举三角形一个起点
B
B
B,然后找到最大的
C
C
C,满足
∠
B
A
C
≤
18
0
o
\angle BAC\le 180^o
∠BAC≤180o。此时,
B
B
B 和
C
C
C 之间任选两点和
B
B
B 组成的三角形一定不包含
A
A
A。
因此,我们可以枚举
A
A
A,对剩下的点按极角序排序,然后枚举
B
B
B,
C
C
C 可以双指针求出(也可以二分求出)。
总复杂度为
O
(
n
2
l
o
g
n
)
O(n^2logn)
O(n2logn)。
代码如下
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void debug_out(){
cerr << endl;
}
template<typename Head, typename... Tail>
void debug_out(Head H, Tail... T){
cerr << ' ' << H;
debug_out(T...);
}
#ifdef local
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 55
#endif
struct P{
ll x, y;
P(ll X = 0, ll Y = 0){
x = X, y = Y;
}
};
P operator - (P a, P b){
return P(a.x - b.x, a.y - b.y);
}
ll cross(P a, P b){
return a.x * b.y - a.y * b.x;
}
int xx(P a){
if(a.x > 0 && a.y >= 0) return 1;
if(a.x <= 0 && a.y > 0) return 2;
if(a.x < 0 && a.y <= 0) return 3;
if(a.x >= 0 && a.y < 0) return 4;
assert(0);
}
int cmp(P a, P b){
if(xx(a) != xx(b)) return xx(a) < xx(b);
return cross(a, b) > 0;
}
ll C(int n, int k){
ll s = 1;
for(int i = n; i >= n - k + 1; i--) s *= i;
for(int i = 1; i <= k; i++) s /= i;
return s;
}
int main() {
#ifdef local
freopen("../in.txt", "r", stdin);
#endif
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T;
cin >> T;
while(T--){
int n;
cin >> n;
vector<P> v(n);
for(int i = 0; i < n; i++) cin >> v[i].x >> v[i].y;
ll ans = C(n, 4);
for(int i = 0; i < n; i++){
ll tmp = C(n - 1, 3);
int nn = n - 1;
vector<P> vv;
for(int j = 0; j < n; j++){
if(j != i){
vv.push_back(v[j] - v[i]);
}
}
sort(vv.begin(), vv.end(), cmp);
int p = 0;
for(int j = 0; j < nn; j++){
p = max(p, j);
while((p + 1) % nn != j && cross(vv[j], vv[(p + 1) % nn]) >= 0) p++;
int k = p - j;
tmp -= k * (k - 1) / 2;
}
ans -= tmp;
}
cout << ans << '\n';
}
return 0;
}