FFT模板(無講解)

GreenDuck發表於2019-03-18
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1E6+5;
 4 const double pi=3.1415926535898;
 5 int n,m,limit,r[maxn*4],len;
 6 struct com
 7 {
 8     double a,b;
 9     com(double A=0,double B=0){a=A,b=B;}
10     void operator=(com x){a=x.a,b=x.b;}
11     com operator+(com x){return com(a+x.a,b+x.b);}
12     com operator-(com x){return com(a-x.a,b-x.b);}
13     com operator*(com x){return com(a*x.a-b*x.b,a*x.b+b*x.a);}
14 }f[maxn*4],g[maxn*4];
15 int re(int x)
16 {
17     int sum=0;
18     for(int i=0;i<len;++i)sum=sum*2+((x&(1<<i))>0);
19     return sum;
20 }
21 void FFT(com*A,int g)
22 {
23     for(int i=0;i<limit;++i)
24         if(i<r[i])swap(A[i],A[r[i]]);
25     for(int i=2;i<=limit;i*=2)
26     {
27         com w(cos(2*pi/i),g*sin(2*pi/i));
28         for(int j=0;j<limit/i;++j)
29         {
30             com d(1,0);
31             for(int k=0;k<i/2;++k)
32             {
33                 com a=A[i*j+k],b=d*A[i*j+i/2+k];
34                 A[i*j+k]=a+b;
35                 A[i*j+i/2+k]=a-b;
36                 d=d*w;
37             }
38         }
39     }
40 }
41 int main()
42 {
43     ios::sync_with_stdio(false);
44     cin>>n>>m;
45     for(int i=0;i<=n;++i)cin>>f[i].a;
46     for(int i=0;i<=m;++i)cin>>g[i].a;
47     limit=1;
48     len=0;
49     while(limit<=n+m+1)
50     {
51         limit*=2;
52         ++len;
53     }
54     for(int i=0;i<limit;++i)r[i]=re(i);
55     FFT(f,1);
56     FFT(g,1);
57     for(int i=0;i<=limit;++i)f[i]=f[i]*g[i];
58     FFT(f,-1);
59     for(int i=0;i<=n+m;++i)cout<<int(f[i].a/limit+0.5)<<' ';
60     cout<<endl;
61     return 0;
62 }
View Code

 

相關文章