hdu1402 A * B Problem Plus 高精度乘法 快速傅里葉變換(FFT)

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

模板題,具體請看代碼註釋

PS:wikioi3123需要把N改爲400005,再去掉printf("\n");即可

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#define N 200005
#define pi acos(-1.0) //PI值 
using namespace std;

struct complex
{
	double r,i;
	complex(double real=0.0,double image=0.0)
	{
		r=real;
		i=image;
	}
	//以下爲三種虛數運算的定義 
	complex operator+(const complex o)
	{
		return complex(r+o.r,i+o.i);
	}
	complex operator-(const complex o)
	{
		return complex(r-o.r,i-o.i);
	}
	complex operator*(const complex o)
	{
		return complex(r*o.r-i*o.i,r*o.i+i*o.r);
	}
}x1[N],x2[N];
char a[N/2],b[N/2];
int sum[N]; //結果存在sum裏 

void brc(complex *y,int l) //二進制平攤反轉置換 O(logn) 
{
	register int i,j,k;
	for(i=1,j=l/2;i<l-1;i++)
	{
		if(i<j)	swap(y[i],y[j]); //交換互爲下標反轉的元素  
								 //i<j保證只交換一次 
		k=l/2;
		while(j>=k) //由最高位檢索,遇1變0,遇0變1,跳出 
		{
			j-=k;
			k/=2;
		}
		if(j<k)	j+=k;
	}
}

void fft(complex *y,int l,double on) //FFT O(nlogn) 
//其中on==1時爲DFT,on==-1爲IDFT 
{
	register int h,i,j,k;
	complex u,t; 
	brc(y,l); //調用反轉置換 
	for(h=2;h<=l;h<<=1) //控制層數 
	{
		//初始化單位復根 
		complex wn(cos(on*2*pi/h),sin(on*2*pi/h));
		for(j=0;j<l;j+=h) //控制起始下標 
		{
			complex w(1,0); //初始化螺旋因子 
			for(k=j;k<j+h/2;k++) //配對 
			{
				u=y[k];
				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<l;i++)
			y[i].r/=l; //IDFT 
}

int main()
{
	int l1,l2,l;
	register int i;
	while(~scanf("%s%s",a,b))
	{
		l1=strlen(a);
		l2=strlen(b);
		l=1;
		while(l<l1*2 || l<l2*2)	l<<=1; //將次數界變成2^n 
					      			   //配合二分與反轉置換 
		for(i=0;i<l1;i++) //倒置存入 
		{
			x1[i].r=a[l1-i-1]-'0';
			x1[i].i=0.0;
		}
		for(;i<l;i++)
			x1[i].r=x1[i].i=0.0;
		//將多餘次數界初始化爲0 
		for(i=0;i<l2;i++)
		{
			x2[i].r=b[l2-i-1]-'0';
			x2[i].i=0.0;
		}
		for(;i<l;i++)
			x2[i].r=x2[i].i=0.0;
		fft(x1,l,1); //DFT(a) 
		fft(x2,l,1); //DFT(b) 
		for(i=0;i<l;i++)
			x1[i]=x1[i]*x2[i]; //點乘結果存入a 
		fft(x1,l,-1); //IDFT(a*b) 
		for(i=0;i<l;i++)
			sum[i]=x1[i].r+0.5; //四捨五入 
		for(i=0;i<l;i++) //進位 
		{
			sum[i+1]+=sum[i]/10;
			sum[i]%=10;
		}
		l=l1+l2-1;
		while(sum[l]<=0 && l>0)	l--; //檢索最高位 
		for(i=l;i>=0;i--)
			putchar(sum[i]+'0'); //倒序輸出 
		printf("\n");
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章