hdu 1402 A * B Problem Plus(FFT)

A * B Problem Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19410    Accepted Submission(s): 4527



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
 

题意:大数乘法;

思路:普通的大数乘法运算量在n^2的时间复杂度,自然会tle,由此联想到fft;

fft 主要是解决卷积的问题,这题中每个数可看做是一个序列,故此可以用fft(fft算法是将普通的表达式转化成点值表达式,转化之后可以再n内求出,算过之后再转化回去就好)

代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5+5;
const double pi = acos(-1.0);
char s[N],s1[N];
struct comp
{
    double r,i;
    comp(double _r=0,double _i=0)
    {
        r=_r;
        i=_i;
    }
    comp operator+(const comp x)
    {
        return comp(r+x.r,i+x.i);
    }
    comp operator-(const comp x)
    {
        return comp(r-x.r,i-x.i);
    }
    comp operator*(const comp x)
    {
        return comp(r*x.r-i*x.i,r*x.i+i*x.r);
    }
} x[N], y[N];
int ans[N];
void FFT(comp a[],int n,int t)
{
    for(int i=1,j=0; i<n-1; i++)
    {
        for(int s=n; j^=s>>=1,~j&s;);
        if(i<j)swap(a[i],a[j]);
    }
    for(int d=0; (1<<d)<n; d++)
    {
        int m=1<<d,m2=m<<1;
        double o=pi/m*t;
        comp _w(cos(o),sin(o));
        for(int i=0; i<n; i+=m2)
        {
            comp w(1,0);
            for(int j=0; j<m; j++)
            {
                comp &A=a[i+j+m],&B=a[i+j],t=w*A;
                A=B-t;
                B=B+t;
                w=w*_w;
            }
        }
    }
    if(t==-1)for(int i=0; i<n; i++)a[i].r/=n;
}

int main()
{
    while(scanf("%s%s", &s,&s1)!=EOF)
    {
        memset(ans,0,sizeof(ans));
        int len1=strlen(s),len2=strlen(s1);
        int len3=max(len1,len2);
        int len=1;
        while(len<len3)len<<=1;
        len<<=1;
        for(int i=0;i<len1;i++)
           x[i]=comp(s[len1-1-i]-'0',0);
        for(int i=len1;i<len;i++)
            x[i]=comp(0,0);
        for(int i=0;i<len2;i++)
            y[i]=comp(s1[len2-1-i]-'0',0);
        for(int i=len2;i<len;i++)
            y[i]=comp(0,0);
        FFT(x,len,1);FFT(y,len,1);
        for(int i=0;i<len;i++)
           x[i]=x[i]*y[i];
        FFT(x,len,-1);
        for(int i=0;i<len;i++)
            ans[i]=x[i].r+0.5;
        for(int i=0;i<len;i++)
        {
            //printf("%d %d\n",ans[i],ans[i+1]);
            ans[i+1]+=ans[i]/10;
            ans[i]%=10;
        }
        len++;
        while(!ans[len])len--;
        for(int i=len;i>0;i--)
            printf("%d",ans[i]);
        printf("%d\n",ans[0]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值