2018.12.31 bzoj3771: Triple(生成函数+fft+容斥原理)

版权声明:随意转载哦......但还是请注明出处吧: https://blog.csdn.net/dreaming__ldx/article/details/85422142

传送门
生成函数经典题。
题意简述:给出 n n 个数,可以从中选 1 / 2 / 3 1/2/3 个,问所有可能的和对应的方案数。


思路:
A ( x ) , B ( x ) , C ( x ) A(x),B(x),C(x) 表示选 1 1 个, 2 2 个, 3 3 个的生成函数, a n s 1 ( x ) , a n s 2 ( x ) , a n s 3 ( x ) ans1(x),ans2(x),ans3(x) 表示选 1 1 个, 2 2 个, 3 3 个答案的生成函数。
那么 a n s 1 ( x ) = A ( x ) ans1(x)=A(x)
a n s 2 ( x ) = A 2 ( x ) B ( x ) ans2(x)=A^2(x)-B(x)
a n s 3 ( x ) = A 3 ( x ) 3 A ( x ) B ( x ) + 2 C ( x ) ans3(x)=A^3(x)-3A(x)B(x)+2C(x)
然后就可以算出答案了。
注意用 f f t fft 优化多项式乘法。
代码:

#include<bits/stdc++.h>
#define ri register int
using namespace std;
const double pi=acos(-1.0);
const int N=5e5+5;
typedef long long ll;
struct Cp{
	double x,y;
	friend inline Cp operator+(const Cp&a,const Cp&b){return (Cp){a.x+b.x,a.y+b.y};}
	friend inline Cp operator-(const Cp&a,const Cp&b){return (Cp){a.x-b.x,a.y-b.y};}
	friend inline Cp operator*(const Cp&a,const Cp&b){return (Cp){a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x};}
	friend inline Cp operator*(const double&a,const Cp&b){return (Cp){a*b.x,a*b.y};}
	friend inline Cp operator/(const Cp&a,const double&b){return (Cp){a.x/b,a.y/b};}
}a[N],b[N],c[N];
int pos[N],lim=1,tim=0,mx=0,n;
inline void init(){
	while(lim<=mx*2)lim<<=1,++tim;
	for(ri i=0;i<lim;++i)pos[i]=(pos[i>>1]>>1)|((i&1)<<(tim-1));
}
inline int read(){
	int ans=0;
	char ch=getchar();
	while(!isdigit(ch))ch=getchar();
	while(isdigit(ch))ans=(ans<<3)+(ans<<1)+(ch^48),ch=getchar();
	return ans;
}
inline void fft(Cp a[],int type){
	for(ri i=0;i<lim;++i)if(i<pos[i])swap(a[i],a[pos[i]]);
	for(ri mid=1;mid<lim;mid<<=1){
		Cp wn=(Cp){cos(pi/mid),type*sin(pi/mid)};
		for(ri j=0,len=mid<<1;j<lim;j+=len){
			Cp w=(Cp){1,0};
			for(ri k=0;k<mid;++k,w=w*wn){
				Cp a0=a[j+k],a1=a[j+k+mid]*w;
				a[j+k]=a0+a1,a[j+k+mid]=a0-a1;
			}
		}
	}
	if(type==-1)for(ri i=0;i<lim;++i)a[i]=a[i]/lim;
}
int main(){
	n=read();
	for(ri i=1,x;i<=n;++i)x=read(),++a[x].x,++b[x*2].x,++c[x*3].x,mx=max(mx,x*3);
	init(),fft(a,1),fft(b,1),fft(c,1);
	for(ri i=0;i<lim;++i)a[i]=(a[i]*a[i]*a[i]-3*a[i]*b[i]+(Cp){2,0}*c[i])/6.0+(a[i]*a[i]-b[i])/2.0+a[i];
	fft(a,-1);
	for(ri i=0;i<=mx;++i){
		ll ans=(ll)(a[i].x+0.5);
		if(ans)cout<<i<<' '<<ans<<'\n';
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/dreaming__ldx/article/details/85422142