[学习笔记]FFT

好久不见. 提交于 2019-12-16 23:07:11

转载大佬的博客

#include <cstdio>
#include <cmath>
const int MAXN = 3000005;
const double pi = acos(-1.0);
int read()
{
    int num=0,flag=1;char c;
    while((c=getchar())<'0'||c>'9')if(c=='-')flag=-1;
    while(c>='0'&&c<='9')num=(num<<3)+(num<<1)+(c^48),c=getchar();
    return num*flag;
}
int n,m,len;
struct complex
{
	double x,y;
	complex() {}
	complex(double X,double Y) : x(X) , y(Y) {}
	complex operator + (const complex &R) const {return complex(x+R.x,y+R.y);}
	complex operator - (const complex &R) const {return complex(x-R.x,y-R.y);}
	complex operator * (const complex &R) const {return complex(x*R.x-y*R.y,x*R.y+y*R.x);} 
}a[MAXN],b[MAXN];
void FFT(int len,complex *a,int flg)
{
	if(len==1) return ;
	complex a1[len>>1],a2[len>>1];
	for(int i=0;i<len;i+=2) a1[i>>1]=a[i],a2[i>>1]=a[i+1];
	FFT(len>>1,a1,flg);FFT(len>>1,a2,flg);
	const complex w=complex(cos(pi*2.0/len),sin(pi*2.0/len)*flg);
	complex k=complex(1,0);len>>=1;
	for(int i=0;i<len;i++,k=k*w)
	{
		a[i]=a1[i]+k*a2[i];
		a[i+len]=a1[i]-k*a2[i];
	}
}
int main()
{
	n=read();m=read();
	for(int i=0;i<=n;i++) a[i].x=read();
	for(int i=0;i<=m;i++) b[i].x=read();
	len=1;while(len<=n+m) len<<=1;
	FFT(len,a,1);FFT(len,b,1);
	for(int i=0;i<=len;i++) a[i]=a[i]*b[i];
	FFT(len,a,-1);
	for(int i=0;i<=n+m;i++)
		printf("%d ",(int)(a[i].x/len+0.5));
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!