题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1402
A * B Problem Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18633 Accepted Submission(s): 4225
Problem Description
Calculate A * B.
Input
Each line will contain two integers A and B. Process to end of file.
Note: the length of each integer will not exceed 50000.
Output
For each case, output A * B in one line.
Sample Input
1
2
1000
2
Sample Output
2
2000
【思路分析】FFT做大整数乘法。
【AC代码】
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define LL long long
const double eps(1e-8);
const double PI=acos(-1.0);
struct Complex
{
double real,image;
Complex(double _real,double _image)
{
real=_real;
image=_image;
}
Complex() {}
};
Complex operator +(const Complex &c1,const Complex &c2)
{
return Complex(c1.real+c2.real,c1.image+c2.image);
}
Complex operator -(const Complex &c1,const Complex &c2)
{
return Complex(c1.real-c2.real,c1.image-c2.image);
}
Complex operator *(const Complex &c1,const Complex &c2)
{
return Complex(c1.real*c2.real-c1.image*c2.image,c1.real*c2.image+c1.image*c2.real);
}
int rev(int id,int len)
{
int ret=0;
for(int i=0; (1<<i)<len; i++)
{
ret<<=1;
if(id&(1<<i))
{
ret|=1;
}
}
return ret;
}
Complex A[140000];
void FFT(Complex *a,int len,int DFT)//对a进行FFT或者逆DFT,结果存在a中
{
for(int i=0; i<len; i++)
{
A[rev(i,len)]=a[i];
}
for(int s=1; (1<<s)<=len; s++)
{
int m=(1<<s);
Complex wm=Complex(cos(DFT*2*PI/m),sin(DFT*2*PI/m));
for(int k=0; k<len; k+=m)
{
Complex w=Complex(1,0);
for(int j=0; j<(m>>1); j++)
{
Complex t=w*A[k+j+(m>>1)];
Complex u=A[k+j];
A[k+j]=u+t;
A[k+j+(m>>1)]=u-t;
w=w*wm;
}
}
}
if(DFT==-1)
{
for(int i=0; i<len; i++)
{
A[i].real/=len;
A[i].image/=len;
}
}
for(int i=0; i<len; i++)
{
a[i]=A[i];
}
return ;
}
char str1[50005],str2[50005];//以每一位数字做为多项式的系数
Complex a[140000],b[140000];//乘积的长度不会超过100000
int ans[140000];
int main()
{
while(~scanf("%s",str1))
{
int len1=strlen(str1);
int sa=0;
while((1<<sa)<len1)sa++;
scanf("%s",str2);
int len2=strlen(str2);
int sb=0;
while((1<<sb)<len2)sb++;
int len=(1<<(max(sa,sb)+1));//成积多项式的次数最多不会超过max(sa,sb)+1
for(int i=0; i<len; i++)
{
if(i<len1)
{
a[i]=Complex(str1[len1-i-1]-'0',0);
}
else
{
a[i]=Complex(0,0);
}
if(i<len2)
{
b[i]=Complex(str2[len2-i-1]-'0',0);
}
else
{
b[i]=Complex(0,0);
}
}
FFT(a,len,1);//把a,b都换成点表达式
FFT(b,len,1);
for(int i=0; i<len; i++)//做点表达式的乘法
{
a[i]=a[i]*b[i];
}
FFT(a,len,-1);//逆DFT换回原来的次数 ,虚部一定都是0
for(int i=0; i<len; i++)
{
ans[i]=(int)(a[i].real+0.5);//取整误差的处理
}
for(int i=0; i<len-1; i++)//进位问题
{
ans[i+1]+=ans[i]/10;
ans[i]%=10;
}
bool flag=0;
for(int i=len-1; i>=0; i--)//输出格式的调整
{
if(ans[i])
printf("%d",ans[i]),flag=1;
else if(flag||i==0)
{
printf("0");
}
}
printf("\n");
}
return 0;
}