题解:P10666 COUNTARI
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;
}