题目大意:给定两个高精度整数,求两个数的乘积
FFT大法好
系统的complex比手写慢了2.5倍 简直吓死人- -
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define M 131080 #define PI 3.1415926535897932384626433832795028841971 using namespace std; namespace PoPoQQQ_Complex{ template<typename T>class Complex{ public: T real,imaginary; Complex() {} Complex(T _,T __=0.0):real(_),imaginary(__) {} Complex& operator += (const Complex<T> &x) { real+=x.real;imaginary+=x.imaginary;return *this; } Complex& operator -= (const Complex<T> &x) { real-=x.real;imaginary-=x.imaginary;return *this; } friend Complex operator + (const Complex<T> &x,const Complex<T> &y) { Complex re=x;re+=y;return re; } friend Complex operator - (const Complex<T> &x,const Complex<T> &y) { Complex re=x;re-=y;return re; } friend Complex operator * (const Complex<T> &x,const Complex<T> &y) { return Complex(x.real*y.real-x.imaginary*y.imaginary,x.real*y.imaginary+x.imaginary*y.real); } Complex& operator *= (const Complex &x) { return *this=(*this)*x; } }; } using namespace PoPoQQQ_Complex; typedef Complex<double> abcd; int n; abcd a[M],b[M],p[M]; char s[M]; void FFT(abcd x[],int n,int type) { static abcd temp[M]; int i; if(n==1) return ; for(i=0;i<n;i+=2) temp[i>>1]=x[i],temp[i+n>>1]=x[i+1]; memcpy(x,temp,sizeof(abcd)*n); abcd *l=x,*r=x+(n>>1); FFT(l,n>>1,type);FFT(r,n>>1,type); abcd root(cos(2*type*PI/n),sin(2*type*PI/n) ),w(1); for(i=0;i<n>>1;i++,w*=root) temp[i]=l[i]+w*r[i],temp[i+(n>>1)]=l[i]-w*r[i]; memcpy(x,temp,sizeof(abcd)*n); } int main() { int i,digit; cin>>n; scanf("%s",s+1); for(i=0;i<n;i++) a[i].real=s[n-i]-'0'; scanf("%s",s+1); for(i=0;i<n;i++) b[i].real=s[n-i]-'0'; for(digit=1;digit<n<<1;digit<<=1); FFT(a,digit,1);FFT(b,digit,1); for(i=0;i<digit;i++) p[i]=a[i]*b[i]; FFT(p,digit,-1); static int stack[M],top; for(i=0;i<=n-1<<1;i++) { ++top; stack[top]+=int(p[i].real/digit+0.5); stack[top+1]+=stack[top]/10; stack[top]%=10; } if(stack[top+1]) ++top; while(top) putchar(stack[top--]+'0'); puts(""); return 0; }
原文地址:http://blog.csdn.net/popoqqq/article/details/42145233