题意:
求两个非负整数相乘,每个整数长度最长不超过50000。
题解:
看到50000长度,我们就知道正常的大数乘法是不行的,因为复杂度n^2太大了。我们需要nlogn的复杂度才行。所以用到了快速傅里叶变换/FFT。
快速傅里叶变换详细的可以自己找资料,这里算是直接贴模板的。
快速傅里叶变换的作用就是在nlogn时间内求的两个多项式的乘积。
对于一个整数a0a1a2,我们可以写成a2+a1*x+a0*x^2。也就是一个x=10的多项式。该题中我们将两个整数都写成这样的形式,然后用快速傅里叶变换求得两个多项式的乘积。那么乘积的系数num[i]就是我们需要求的乘积的各个位数值了。由于各个位数值有可能会超过10,所以需要重新遍历处理下。
以下模板代码写的很犀利,我不知道是从哪个大神那弄来的。。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=200020;
const double pi=atan(1.0)*4;
struct complex{//复数,重载+,-,*
double a,b;
complex(double aa=0,double bb=0){a=aa;b=bb;}
complex operator +(const complex &e){return complex(a+e.a,b+e.b);}
complex operator -(const complex &e){return complex(a-e.a,b-e.b);}
complex operator *(const complex &e){return complex(a*e.a-b*e.b,a*e.b+b*e.a);}
};
void change(complex y[],int len)
{
int i,j,k;
for(i=1,j=len/2;i<len-1;i++)
{
if(i<j)swap(y[i],y[j]);
k=len/2;
while(j>=k)
{
j-=k;
k/=2;
}
if(j<k)j+=k;
}
}
//FFT快速傅里叶变换的模板,用以将多项式系数转换成单位根(??应该是),这样得到的两个序列逐个相乘到得就是系数
//序列的卷积,即两个多项式乘积后的系数值
void fft(complex y[],int len,int on)
{
change(y,len);
int i,j,k,h;
for(h=2;h<=len;h<<=1)
{
complex wn(cos(-on*2*pi/h),sin(-on*2*pi/h));
for(j=0;j<len;j+=h)
{
complex w(1,0);
for(int k=j;k<j+h/2;k++)
{
complex u=y[k];
complex t=w*y[k+h/2];
y[k]=u+t;
y[k+h/2]=u-t;
w=w*wn;
}
}
}
if(on==-1)
for(i=0;i<len;i++)
y[i].a/=len;
}
int num[maxn];
complex x1[maxn],x2[maxn];
char s1[maxn/4],s2[maxn/4];
int main()
{
//freopen("D:\\in.txt","r",stdin);
//freopen("D:\\false.txt","w",stdout);
while(scanf("%s%s",s1,s2)!=EOF)
{
int n,i,j,k;
int len1,len2,len=1,ans=0;
len1=strlen(s1);
len2=strlen(s2);
//cout<<len1<<" "<<len2<<endl;
//两个多项式长n,m,那么乘积长n+m-1,
//这里求最接近且大于n+m-1的2^k,方便二叉树形式的运用吧
while(len<len1+len2)len<<=1;
//cout<<"*"<<len<<endl;
//cout<<len<<endl;
for(i=0;i<len1;i++)
x1[i]=complex(s1[len1-1-i]-'0',0);
for(i=len1;i<len;i++)
x1[i]=complex(0,0);
for(i=0;i<len2;i++)
x2[i]=complex(s2[len2-1-i]-'0',0);
for(i=len2;i<len;i++)
x2[i]=complex(0,0);
fft(x1,len,1);//FFT转换成单位根形式
fft(x2,len,1);
for(i=0;i<len;i++)
x1[i]=x1[i]*x2[i];//卷积
fft(x1,len,-1);//结果转换回来
int temp=0;
for(i=0;i<len;i++)
{
temp=temp+(int)(x1[i].a+0.5);
num[i]=temp%10;
temp=temp/10;
}
while(temp)
{
num[len++]=temp%10;
temp=temp/10;
}
i=len-1;
while(num[i]==0&&i>0)i--;
for(;i>=0;i--)
printf("%d",num[i]);
printf("\n");
}
return 0;
}