【BZOJ】【2179】FFT快速傅里叶
FFT
做的第二道用到FFT的……好吧其实还是模板题-_-b
百度上说好像分治也能做……不过像FFT这种敲模板的还是省事=。=
1 /************************************************************** 2 Problem: 2179 3 User: Tunix 4 Language: C++ 5 Result: Accepted 6 Time:1236 ms 7 Memory:9184 kb 8 ****************************************************************/ 9 10 //BZOJ 2179 11 #include<cmath> 12 #include<cstdio> 13 #include<cstring> 14 #include<cstdlib> 15 #include<iostream> 16 #include<algorithm> 17 #define rep(i,n) for(int i=0;i<n;++i) 18 #define F(i,j,n) for(int i=j;i<=n;++i) 19 #define D(i,j,n) for(int i=j;i>=n;--i) 20 using namespace std; 21 void read(int &v){ 22 v=0; int sign=1; char ch=getchar(); 23 while(ch<'0'||ch>'9'){ if (ch=='-') sign=-1; ch=getchar();} 24 while(ch>='0'&&ch<='9'){ v=v*10+ch-'0'; ch=getchar();} 25 v*=sign; 26 } 27 /******************tamplate*********************/ 28 #define debug 29 const int N=150010; 30 const double pi=acos(-1.0); 31 struct comp{ 32 double r,i; 33 comp(double _r=0.0,double _i=0.0):r(_r),i(_i){} 34 // comp(){} 35 comp operator+(const comp &b)const{return comp(r+b.r,i+b.i);} 36 comp operator-(const comp &b)const{return comp(r-b.r,i-b.i);} 37 comp operator*(const comp &b)const{return comp(r*b.r-i*b.i,r*b.i+i*b.r);} 38 }a[N],b[N],c[N]; 39 40 void FFT(comp *a,int n,int type){ 41 for(int i=1,j=0;i<n-1;++i){//只需改变1~n-2,0和n-1两个位置不变 42 for(int s=n;j^=s>>=1,~j&s;); 43 if (i<j) swap(a[i],a[j]); 44 } 45 for(int m=1;m<n;m<<=1){ 46 double u=pi/m*type; comp wm(cos(u),sin(u)); 47 for(int i=0;i<n;i+=(m<<1)){ 48 comp w(1,0); 49 rep(j,m){ 50 comp &A=a[i+j+m],&B=a[i+j],t=w*A; 51 A=B-t; B=B+t; w=w*wm; 52 } 53 } 54 } 55 if (type==-1) rep(i,n) a[i].r/=n; 56 } 57 char s1[N],s2[N]; 58 int ans[N]; 59 int main(){ 60 int n,k; 61 read(n); 62 scanf("%s%s",s1,s2); 63 rep(i,n){ 64 a[i].r=s1[n-i-1]-'0'; 65 b[i].r=s2[n-i-1]-'0'; 66 } 67 for(k=1;k<=n*2;k<<=1); 68 FFT(a,k,1); FFT(b,k,1); 69 F(i,0,k) c[i]=a[i]*b[i]; 70 FFT(c,k,-1); 71 F(i,0,n*2) 72 ans[i]=c[i].r+0.4; 73 int temp=0; 74 F(i,0,n*2){ 75 if (ans[i]) temp=i; 76 ans[i+1]+=ans[i]/10; 77 ans[i]%=10; 78 } 79 D(i,temp,0) printf("%d",ans[i]); 80 return 0; 81 }