跳到正文

题解

题解 CF1284E 【New Year and Castle Construction】

jiazhaopeng约 5 分钟
原文
文章信息与版本

文章信息

发布
2021年5月13日
收录
2025年12月30日
更新
2026年11月3日
篇幅
约 5 分钟
题目
CF1284E

版本

  1. v1当前

这里提供一种新的做法。

用四边形框起来一个点看起来比较难统计,而用三角形框住一个点则较为简单。设四边形的方案数为 YY,三角形的方案数为 XX。可以发现,Y=(n−4)2XY = \frac{(n-4)}{2}X。证明:对于一种四边形(不一定是凸四边形)框一个点的情况,可以连上任意一条对角线,转化为三角形框一个点后再选一个点(可以在三角形内部)。并且如果我们按 (n−4)X(n-4)X 计数的话每种四边形的情况会被算恰好两遍(因为选每条对角线都会被算一次)。

考虑如何计算 XX。枚举被框住的点 AA,将其余点极角排序。枚举两个点 B,CB,C,第三个点可以是图中阴影部分的点。直接做可以做到 O(n3)O(n^3)。

CF1284E

前缀和优化一下,大概是 SB−SCS_B - S_C 的形式,其中 SBS_B 表示一条射线从 YY 轴负方向逆时针旋转到 BA→\overrightarrow{BA} 所经过的点的数量。通过处理 SCS_C 的前缀和,我们可以在枚举 BB 的时候计算所有 CC 的贡献。复杂度 O(n2)O(n^2),算上极角排序的复杂度为 O(n2log⁡n)O(n^2 \log n)。

还是有一些细节的。具体细节看代码吧。

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cctype>
#define N 2511
typedef long long ll;
template<typename T> inline void read(T &x) {
	x = 0; char c = getchar(); bool flag = false;
	while (!isdigit(c)) { if (c == '-') flag = true; c = getchar(); }
	while (isdigit(c)) x = x * 10 + (c ^ 48), c = getchar();
	if (flag)	x = -x;
}
using namespace std;
int n;
struct Vectors {
	ll x, y;
	Vectors(ll xx = 0, ll yy = 0) { x = xx, y = yy; }
	inline Vectors operator +(const Vectors &a) const {
		return Vectors(x + a.x, y + a.y);
	}
	inline Vectors operator -(const Vectors &a) const {
		return Vectors(x - a.x, y - a.y);
	}
	inline ll operator *(const Vectors &a) const {
		return x * a.y - y * a.x;
	}
}vt[N], h[N];
int htot;
ll ans;
inline bool cmp(const Vectors &a, const Vectors &b) {//极角排序
	if (a.y < 0 && b.y > 0)	return true;
	if (a.y > 0 && b.y < 0)	return false;
	if (a.y == 0 && a.x < 0) return true;
	if (b.y == 0 && b.x < 0) return false;
	return a * b > 0;
}
int f[N], sum[N];
inline void calc(int p) {
	htot = 0;
	for (int i = 1; i <= n; ++i) if (i != p) h[++htot] = vt[i] - vt[p];
	sort(h + 1, h + 1 + htot, cmp);
	int ptr = htot;//上下方的分界点
	for (int i = 1; i <= htot; ++i) if (h[i].y > 0 || (h[i].y == 0 && h[i].x > 0)) {
		ptr = i; break;
	}
	int pt = htot - 1;
	for (int i = htot; i >= ptr; --i) {//双指针求 S_A
		while (pt && h[pt] * h[i] > 0) --pt;
		f[i] = pt;
	}
	sum[ptr - 1] = 0;
	for (int i = ptr; i <= htot; ++i) sum[i] = sum[i - 1] + f[i];//前缀和优化计算答案
	for (int i = ptr + 1; i <= htot; ++i) {
		ans += f[i] * (i - ptr) - sum[i - 1];
	}
}
int main() {
	read(n);
	for (int i = 1; i <= n; ++i) read(vt[i].x), read(vt[i].y);
	for (int i = 1; i <= n; ++i) calc(i);//统计 B,C 都在 A 上方的情况
	for (int i = 1; i <= n; ++i) vt[i].x = -vt[i].x, vt[i].y = -vt[i].y;
	for (int i = 1; i <= n; ++i) calc(i);//统计 B,C 都在 A 下方的情况
	ans = (ans * (n - 4)) >> 1;
	printf("%lld\n", ans);
	return 0;
}
原文