模板FFT
Posted xuyixuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板FFT相关的知识,希望对你有一定的参考价值。
题意简述
求两个多项式的卷积
题解思路
先将多项式转化为点值表示法,再相乘,最后转化为系数表示法
注意:用三次变两次优化会掉精
代码(递归)
#include <cmath>
#include <cstdio>
const int N=4000010;
const double Pi=acos(-1.0);
int n,m,len=1;
struct Complex
double x,y;
Complex(double xx=0,double yy=0) x=xx; y=yy;
a[N],b[N];
Complex operator +(Complex x,Complex y) return Complex(x.x+y.x,x.y+y.y);
Complex operator -(Complex x,Complex y) return Complex(x.x-y.x,x.y-y.y);
Complex operator *(Complex x,Complex y) return Complex(x.x*y.x-x.y*y.y,x.x*y.y+x.y*y.x);
void FFT(Complex *x,const int& len,const int& type)
if (len==1) return;
Complex x1[len>>1],x2[len>>1];
for (register int i=0;i<len;i+=2)
x1[i>>1]=x[i]; x2[i>>1]=x[i+1];
FFT(x1,len>>1,type); FFT(x2,len>>1,type);
Complex UR=Complex(cos(2.0*Pi/len),type*sin(2.0*Pi/len)),w=Complex(1,0);
for (register int i=0,_n=len>>1;i<_n;++i,w=w*UR)
x[i]=x1[i]+x2[i]*w;
x[i+_n]=x1[i]-x2[i]*w;
int main()
scanf("%d%d",&n,&m);
for (register int i=0;i<=n;++i) scanf("%lf",&a[i].x);
for (register int i=0;i<=m;++i) scanf("%lf",&b[i].x);
n+=m; for (;len<=n;len<<=1);
FFT(a,len,1); FFT(b,len,1);
for (register int i=0;i<=len;++i) a[i]=a[i]*b[i];
FFT(a,len,-1);
for (register int i=0;i<=n;++i) printf("%d%c",(int)(a[i].x/len+0.5)," \n"[i==n]);
代码(非递归)
#include <cmath>
#include <cctype>
#include <cstdio>
#include <algorithm>
const int N=4000010;
const double Pi=acos(-1.0);
int n,m,lim=1,l=-1,r[N];
char ch;
inline int read() for (;!isdigit(ch=getchar());); return ch-48;
struct Complex
double x,y;
Complex(double xx=0,double yy=0) x=xx; y=yy;
a[N];
Complex operator +(Complex x,Complex y) return Complex(x.x+y.x,x.y+y.y);
Complex operator -(Complex x,Complex y) return Complex(x.x-y.x,x.y-y.y);
Complex operator *(Complex x,Complex y) return Complex(x.x*y.x-x.y*y.y,x.x*y.y+x.y*y.x);
inline void FFT(Complex *x,const int& lim,const int& type)
for (register int i=0;i<lim;++i) if (i<r[i]) std::swap(x[i],x[r[i]]);
for (register int i=1;i<lim;i<<=1)
Complex UR(cos(Pi/i),sin(Pi/i)*type);
for (register int j=0,I=i<<1;j<lim;j+=I)
Complex w(1,0);
for (register int k=0;k<i;++k,w=w*UR)
Complex t1=x[j+k],t2=w*x[k+i+j];
x[j+k]=t1+t2; x[j+k+i]=t1-t2;
int main()
scanf("%d%d",&n,&m);
for (register int i=0;i<=n;++i) a[i].x=read();
for (register int i=0;i<=m;++i) a[i].y=read();
n+=m; for (;lim<=n;lim<<=1,++l);
for (register int i=0;i<lim;++i) r[i]=(r[i>>1]>>1)|((i&1)<<l);
FFT(a,lim,1);
for (register int i=0;i<lim;++i) a[i]=a[i]*a[i];
FFT(a,lim,-1);
for (register int i=0;i<=n;++i) printf("%d%c",(int)(a[i].y/lim/2+0.5)," \n"[i==n]);
以上是关于模板FFT的主要内容,如果未能解决你的问题,请参考以下文章