bzoj2179: FFT快速傅立叶
一句话题意:给出两个n位10进制整数x和y,你需要计算x*y。n<=60000
思路:FFT就是神奇的公式多。。。感觉还没有完全理解
#include<cmath> #include<cstdio> #include<cstring> #include<algorithm> #define ll long long const int maxn=200010; const double pi=M_PI; using namespace std; struct plex{ double r,i; void clear(){r=i=0;} }tmp[maxn]; plex operator +(plex a,plex b){return (plex){a.r+b.r,a.i+b.i};} plex operator -(plex a,plex b){return (plex){a.r-b.r,a.i-b.i};} plex operator *(plex a,plex b){return (plex){a.r*b.r-a.i*b.i,a.r*b.i+a.i*b.r};} char s[maxn];int nn,ans[maxn]; struct DFT{ plex a[maxn]; void read(){ scanf("%s",s); int n=strlen(s),m; for (int i=n-1;i>=0;i--) a[n-i-1].r=s[i]-'0'; for (m=1;m<=n;m<<=1);m<<=1; nn=max(nn,m); } void fft(int bg,int step,int size,int op){ if (size==1) return; fft(bg,step*2,size/2,op),fft(bg+step,step*2,size/2,op); plex w=(plex){1,0},t=(plex){cos(2*pi/size),sin(2*op*pi/size)};//w是n次单位根,乘一次t就能得到下一个w int p=bg,p0=bg,p1=bg+step; for (int i=0;i<size/2;i++){ tmp[p]=a[p0]+w*a[p1]; tmp[p+size/2*step]=a[p0]-w*a[p1]; p+=step,p0+=step*2,p1+=step*2,w=w*t; } for (int i=bg;size;size--,i+=step) a[i]=tmp[i]; } }a,b,c; int main(){ scanf("%d",&nn); a.read(),b.read(); a.fft(0,1,nn,1),b.fft(0,1,nn,1); for (int i=0;i<nn;i++) c.a[i]=a.a[i]*b.a[i];//点值表示时直接乘 c.fft(0,1,nn,-1);ll x=0; for (int i=0;i<nn;i++){ c.a[i].r/=nn;//逆变换时要多除一个n x+=1ll*round(c.a[i].r); ans[i]=x%10,x/=10; } for (;nn&&!ans[nn];nn--);//去前导零 printf("%d",ans[nn--]); for (int i=nn;i>=0;i--) printf("%01d",ans[i]);puts(""); return 0; }
直接上FFT