P10666 COUNTARI Solution
思路
题面已经足够直白了,因此在这里直接写思路。
题面 显然可以先转化为 ,考虑枚举 ,于是题目就转化为了要快速求下面这个式子:
注意到题目标签里有 FFT 我们要算的式子中和为定值,但是 FFT 计算的卷积必须要是下标之和为定值,又看到 序列取值范围挺小的,所以可以把式子转化为用计数器表示的形式:
其中 表示 序列的最大值, 表示序列中下标小于 且数值等于 的数的个数。 的定义同理。
但是这个 和 还和 有关,又不方便在每次移动 的时候动态维护,非常难搞。
这个时候,我们就要发挥惊人的注意力发现题目标签还有一个分块。分块的思想就是在块内暴力做,在整块上整体做。考虑把贡献分开考虑:
- 在整块左侧, 在整块右侧:这种贡献在整个块上都不变,对整块左边的 和整块右边的 进行一次卷积之后,直接累加答案就行。
- 在块中 左侧, 在整块右侧:大力枚举 ,用 计算。
- 在整块左侧, 在块中 右侧:大力枚举 ,用 计算。
- 在块中 左侧, 在块中 右侧:随便大力枚举 或 ,用块内桶计算。
发现 (4) 可以和 (2) 或 (3) 合并计算。具体实现细节可以参考代码实现。
接下来考虑块长 :这个做法的时间复杂度是 ,为了让这个式子最小,使用基本不等式可以直接得出:
当且仅当 ,即 时取得最小值。
综上,把块长 设为 最优。
代码实现
#include <bits/stdc++.h>
#if __linux__
#define ge getchar_unlocked
#define pu putchar_unlocked
#else
#define ge getchar
#define pu putchar
#endif
using namespace std;
char ch;
template <typename T>
inline void read(T &x) {
x=0;while ('0'>ch||ch>'9') ch=ge()
while ('0'<=ch&&ch<='9') x=x*10+ch-'0', ch=ge();
}
typedef long long ll;
typedef double db;
const int N = 1e5+4, A = 1<<16|7;
const db pi = 3.14159265358979323846264338;
int n, a[N], k, rev[A], L, lcnt[A], rcnt[A];
ll ans;
struct comp{
db x, y;
inline comp operator+(const comp &other)const{return {x+other.x, y+other.y};}
inline comp operator-(const comp &other)const{return {x-other.x, y-other.y};}
inline comp operator*(const comp &other)const{return {x*other.x-y*other.y, y*other.x+x*other.y};}
}s[A], p[A], q[A];
inline comp w(int _n, int i){return s[k/_n*i];}
inline void fft(comp *a, bool f){ // FFT 模版
for (int i=0;i<k;++i) if (i<rev[i]) swap(a[i], a[rev[i]]);
for (int len=2;len<=k;len<<=1){
int mid = len>>1;
for (int l=0;l<k;l+=len){
for (int i=l;i<l+mid;++i){
comp x = w(len, f?i-l:len-i+l)*a[i+mid];
a[i+mid] = a[i] - x;
a[i] = a[i] + x;
}
}
}
}
int main() {
read(n);
for (int i=0;i<n;++i) read(a[i]), k = max(k, a[i]), ++rcnt[a[i]];
int lgn = __lg(k*2+1)+1; // 卷积上限是 max a_i
k = 1<<lgn;
L = ceil(sqrt(k*lgn)); // 计算块长
for (int i=0;i<k;++i){ // 预处理单位根和数位的翻转
s[i] = {cos(2*pi*i/k), sin(2*pi*i/k)};
rev[i] = (rev[i>>1]>>1)|((i&1)<<lgn-1);
}
s[k] = s[0];
for (int l=0;l<n;l+=L){
int r = min(l+L, n);
// 此时 lcnt 是 [0..l-1] 的值,rcnt 是 [l..n-1] 的值
for (int i=l;i<r;++i){
--rcnt[a[i]]; // 边算边更新 rcnt 是为了合并上述情况 (4) 和 (2)
for (int j=l;j<i;++j) if (a[i]*2-a[j]>0) ans += rcnt[a[i]*2-a[j]];
for (int j=i+1;j<r;++j) if (a[i]*2-a[j]>0) ans += lcnt[a[i]*2-a[j]];
// 不能同时更新 lcnt,否则 (4) 情况会算 2 遍
}
// FFT 卷积计算情况 (1) 的答案
for (int i=0;i<k;++i) p[i] = {(db)lcnt[i], 0}, q[i] = {(db)rcnt[i], 0};
fft(p, 1), fft(q, 1);
for (int i=0;i<k;++i) p[i] = p[i] * q[i];
fft(p, 0);
for (int i=0;i<k;++i) p[i].x = round(p[i].x/k);
for (int i=l;i<r;++i) ans += ll(p[a[i]*2].x), ++lcnt[a[i]]; // 累计答案并更新 lcnt
}
printf("%lld", ans);
return 0;
}