1. 程式人生 > >HDU 1402 A*B

HDU 1402 A*B

clas out har == using 3.1 int debug amp

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ms(s,a) memset(s,a,sizeof(s))
#define debug(x) cout<<"< "#x" = "<<x<<" >\n"
const double pi=3.1415926536;

const int maxn=3e5+5;
complex<double> a[maxn],b[maxn],c[maxn];

void rearrange(complex<double> x[],int n)
{
    for(int i=1,j=n/2;i<n;++i)
    {
        if(i<j)swap(x[i],x[j]);
        int tmp=n/2;
        while(tmp&&j>=tmp){j-=tmp;tmp/=2;}
        if(j<tmp)j+=tmp;
    }
}
void fft(complex<double> x[],int n,int sig)
{
    rearrange(x,n);
    for(int i=2;i<=n;i*=2)
    {
        for(int j=0;j<n;j+=i)
        {
            for(int k=j;k<j+i/2;++k)
            {
                complex<double> e=x[k],o=x[k+i/2],w=exp(complex<double>(0,sig*2.*pi*(k-j)/i));
                x[k]=e+w*o;
                x[k+i/2]=e-w*o;
            }
        }
    }
    if(sig==-1)
    {
        for(int i=0;i<n;++i)x[i]/=n;
    }
}
int main()
{
    char A[50005],B[50005];
    while(~scanf("%s%s",A,B))
    {
        int la=strlen(A),lb=strlen(B);
        int tot=1;
        while(tot<la+lb-1)tot*=2;
        for(int i=0;i<tot;++i)
        {
            int tmp=0;
            if(i<la)tmp=A[i]-‘0‘;
            a[i]=tmp;
        }
        for(int i=0;i<tot;++i)
        {
            int tmp=0;
            if(i<lb)tmp=B[i]-‘0‘;
            b[i]=tmp;
        }
        fft(a,tot,1);fft(b,tot,1);
        for(int i=0;i<tot;++i)c[i]=a[i]*b[i];
        fft(c,tot,-1);
        //for(int i=0;i<la+lb-1;++i)printf("%lf,",c[i].real());
        //printf("\n");
        int ans[maxn],top=la+lb-2;
        memset(ans,0,sizeof ans);
        for(int i=0;i<tot;++i)
        {
            ans[i]=ans[i]+c[la+lb-2-i].real()+0.5;
            if(i>la+lb-3&&ans[i]==0)break;
            if(ans[i]>9)
            {
                ans[i+1]=ans[i]/10;
                ans[i]%=10;
                if(i>la+lb-3)top++;
            }

        }
        while(top>0&&ans[top]==0)top--;
        while(top>-1)printf("%d",ans[top--]);
        printf("\n");
    }
}

HDU 1402 A*B