#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <cmath> using namespace std; #define maxn 400040 #define LL __int64 const double pi=atan(1.0)*4; struct complex{//复数,重载+,-,* double a,b; complex(double aa=0,double bb=0){a=aa;b=bb;} complex operator +(const complex &e){return complex(a+e.a,b+e.b);} complex operator -(const complex &e){return complex(a-e.a,b-e.b);} complex operator *(const complex &e){return complex(a*e.a-b*e.b,a*e.b+b*e.a);} }; void change(complex y[],LL len) { LL i,j,k; for(i=1,j=len/2;i<len-1;i++) { if(i<j)swap(y[i],y[j]); k=len/2; while(j>=k) { j-=k; k/=2; } if(j<k)j+=k; } } //FFT快速傅里叶变换的模板,用以将多项式系数转换成单位根(??应该是),这样得到的两个序列逐个相乘到得就是系数 //序列的卷积,即两个多项式乘积后的系数值 void fft(complex y[],LL len,LL on) { change(y,len); LL i,j,k,h; for(h=2;h<=len;h<<=1) { complex wn(cos(-on*2*pi/h),sin(-on*2*pi/h)); for(j=0;j<len;j+=h) { complex w(1,0); for(LL k=j;k<j+h/2;k++) { complex u=y[k]; complex t=w*y[k+h/2]; y[k]=u+t; y[k+h/2]=u-t; w=w*wn; } } } if(on==-1) for(i=0;i<len;i++) y[i].a/=len; } LL num[maxn],sum[maxn]; complex x[maxn]; LL a[maxn/4]; int main() { LL T; scanf("%I64d",&T); while(T--) { LL n,i,j,k,maxa=-1; scanf("%I64d",&n); memset(num,0,sizeof(num)); for(i=0;i<n;i++) { scanf("%I64d",&a[i]); //存储个数,用以表示多项式的系数,其中未知数的指数表示长度,这样两个相同多项式乘积的系数表示取两根木棍 //其和是对应指数的组合个数(多项式相乘,系数相乘,指数相加) num[a[i]]++; maxa=max(maxa,a[i]); } sort(a,a+n); LL len1,len=1,ans=0; len1=maxa+1; //两个多项式长n,m,那么乘积长n+m-1, //这里求最接近且大于n+m-1的2^k,方便二叉树形式的运用吧 while(len<2*len1)len<<=1; for(i=0;i<len1;i++) x[i]=complex(num[i],0); for(i=len1;i<len;i++) x[i]=complex(0,0); fft(x,len,1);//FFT转换成单位根形式 for(i=0;i<len;i++) x[i]=x[i]*x[i];//卷积 fft(x,len,-1);//结果转换回来 for(i=0;i<len;i++) num[i]=(LL)(x[i].a+0.5); len=maxa*2; //去掉取形同木棍 for(i=0;i<n;i++) num[a[i]*2]--; //去掉两根木棍左右交换的重复 for(i=1;i<=len;i++) num[i]/=2; sum[0]=0; for(i=1;i<=len;i++) sum[i]=sum[i-1]+num[i]; for(i=0;i<n;i++) { //两根木棍和大于a[i]的个数,三角形任意两边之和大于第三边,这里取的是较小两边,所以要减去大于a[i]的木棍 ans+=sum[len]-sum[a[i]]; //木棍,一根小于a[i],一根大于a[i](这里的大于,小于只是说在i的前后位置) ans-=(n-1-i)*i; //有根木棍取了自身的 ans-=n-1; //两根木棍都大于a[i] ans-=(n-1-i)*(n-2-i)/2; } LL t=n*(n-1)*(n-2)/6; printf("%.7lf\n",(double)ans/t); } return 0; }
大神的解释很犀利,清楚:HDU 4609 3-idiots(FFT)