BZOJ 3513: [MUTC2013]idiots(fft)

传送门

解题思路

  正的不好算考虑倒着,就是用总方案\(-\)不合法方案数。设\(f[i]\)为长度为\(i\)的木棍数,\(g[i]\)为两根木棍长度之和为\(i\)的方案数。那么有转移方程\(g[i]=\sum\limits_{j=1}^{i-1}f[j]*f[i-j]\),这个东西是卷积的形式,可以\(fft\)加速一下。然后最后统计不合法方案数的时候就维护一个\(g[i]\)前缀和,对于一个\(k\)来说,可以产生\(sum[k]*f[k]\)的贡献,就是两根木棍构成\(k\)的方案与一根木棍构成\(k\)的方案之和。最后还需要去一下重,偶数的时候\(i/2\)会被算两次。记得不合法方案数要\(/2\)

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>

using namespace std;
const int MAXN = 400005;
const double Pi = acos(-1);
typedef long long LL;

inline int rd(){
	int x=0,f=1;char ch=getchar();
	while(!isdigit(ch)) {f=ch=='-'?0:1;ch=getchar();}
	while(isdigit(ch))  {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return f?x:-x;
}

int T,n,a[MAXN],rev[MAXN],mx,limit,g[MAXN];
LL ans,sum,tot;
struct Complex{
	double x,y;
	Complex(double xx=0,double yy=0){
		x=xx;y=yy;
	}
}f[MAXN<<1];

Complex operator+(const Complex A,const Complex B){return Complex(A.x+B.x,A.y+B.y);}
Complex operator-(const Complex A,const Complex B){return Complex(A.x-B.x,A.y-B.y);}
Complex operator*(const Complex A,const Complex B){return Complex(A.x*B.x-A.y*B.y,A.x*B.y+A.y*B.x);}

inline int max(int x,int y){
	return x>y?x:y;
}

inline LL C(int x){
	return (LL)x*(x-1)*(x-2)/6;
}

void fft(Complex *f,int type){
	for(int i=0;i<limit;i++) 
		if(i<rev[i]) swap(f[i],f[rev[i]]);
	Complex Wn,w,tmp;int len;
	for(int p=2;p<=limit;p<<=1){
		len=p>>1;Wn=Complex(cos(Pi/len),type*sin(Pi/len));
		for(int k=0;k<limit;k+=p){
			w=Complex(1,0);
			for(int l=k;l<k+len;l++){
				tmp=w*f[l+len];f[l+len]=f[l]-tmp;
				f[l]=f[l]+tmp;w=w*Wn;
			}
		}
	}
}

signed main(){
	T=rd();
	while(T--){
		n=rd();limit=1;ans=0;tot=0;
		for(int i=1;i<=n;i++) a[i]=rd(),mx=max(mx,a[i]),g[a[i]]++;
		for(int i=1;i<=mx;i++) f[i].x=g[i];
		while(limit<=2*mx) limit<<=1;
		for(int i=0;i<limit;i++) rev[i]=(rev[i>>1]>>1)|((i&1)?limit>>1:0); 
		fft(f,1);for(int i=0;i<limit;i++) f[i]=f[i]*f[i];fft(f,-1);
		for(int i=0;i<=mx;i++)
			tot+=(LL)(f[i].x/limit+0.5)-((i&1)?0:g[i/2]),ans+=tot*g[i];
		ans/=2;sum=C(n);
		printf("%.7lf\n",1.0-(double)ans/sum);
		memset(g,0,sizeof(g));
		for(int i=0;i<limit;i++) f[i].x=f[i].y=0;
	}
	return 0;
}
posted @ 2018-11-26 17:56  Monster_Qi  阅读(216)  评论(0编辑  收藏  举报