P1919 [Template] A*B Problem Upgraded Version (FFT Fast Fourier)

Topic description

Given two n-digit decimal integers x and y, you need to compute x*y.

Input and output format

Input format:

 

The first line contains a positive integer n. The second line describes a positive integer x with n digits. The third line describes a positive integer y with n digits.

 

Output format:

 

Output one line, the result of x*y. (note the leading 0)

 

Input and output example

Input Example #1:  Copy
1
3
4
Output Sample #1:  Copy
12

illustrate

data range:

n<=60000

Source: bzoj2179

 

// problem: P1919 [Template] A*B Problem upgraded version (FFT Fast Fourier) 

#include <iostream> 
#include <cstdio> 
#include <cmath> 
#include <cstring> 
#include <algorithm>
 using  namespace std;

const int N=2e5+5;
const double Pi=acos(-1);

int n,m;
int rev[N];
char s[N];
int bit,len=1;
struct Complex
{
    double x,y;
    Complex(double xx=0,double yy=0){x=xx,y=yy;}
    Complex operator + (const Complex &a)
    {
        return Complex(this->x + a.x,this->y + a.y);
    }
    Complex operator - (const Complex &a)
    {
        return Complex(this->x - a.x,this->y - a.y);
    }
    Complex operator * (const Complex &a)
    {
        return Complex(this->x * a.x - this->y * a.y, this->x * a.y + this->y * a.x);
    }
}a[N],b[N];

inline int read()
{
    char c=getchar();int num=0;
    for(;!isdigit(c);c=getchar());
    return c^'0';
}

void fft(Complex *A,int type)
{
    for(int i=0;i<len;++i)
        if(i<rev[i])
            swap(A[i],A[rev[i]]);
    for(int step=1;step<len;step<<=1)
    {
        Complex wn(cos(Pi/step),type*sin(Pi/step));
        for(int j=0;j<len;j+=step<<1)
        {
            Complex wnk(1,0);
            for(int k=j;k<step+j;++k)
            {
                Complex x=A[k];
                Complex y=wnk*A[k+step];
                A[k] =x+ y;
                A[k+step]=x-y;
                wnk = wnk* wn;
            }
        }
    }
}

int ans[N];
intmain ()
{
    scanf("%d",&n);
    for(int i=n-1;i>=0;--i)
        a[i].x=read();
    for(int i=n-1;i>=0;--i)
        b[i].x=read();
    while(len<=n*2)
        len<<=1,++bit;
    for(int i=0;i<len;++i)
        rev[i]=(rev[i>>1]>>1)|((i&1)<<(bit-1));
    fft(a,1);
    fft(b,1);
    for(int i=0;i<=len;++i)
        a[i]=a[i]*b[i];
    fft(a,-1);
    int front=0,R=n<<1;
    for(;(int)(a[R].x/len+0.5)==0;--R);
    for(int i=0;i<=R;++i)
        ans[i]=(int)(a[i].x/len+0.5);
    for(int i=0;i<=R;++i)
    {
        if(ans[i]>=10)
        {
            years[i + 1 ]+=years[i]/ 10 ;
            years[i] %= 10 ;
        }
    }
    if(ans[R+1])
        ++R;
    for(int i=R;i>=0;--i)
        printf("%d",ans[i]);
    return 0;
}

/*
10
9789344841
4839019669

47370832232222677629
*/

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325125846&siteId=291194637