2

A*B problem(FFT)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#define pi acos(-1)
#define rep(i,x,y) for(register int i = x; i <= y;++i)
using namespace std;
const int N = 3e5;
struct cpx
{
    double r,i;
    cpx(){ }
    cpx(double x, double y) { r = x;i = y; }
    inline cpx operator *(const cpx&x)const{
        return cpx(r*x.r - i*x.i,r*x.i + i*x.r );
    }
    inline cpx operator *=(const cpx&x){
        *this = *this * x;
    }
    inline cpx operator +(const cpx&x)const{
        return cpx(r + x.r,i + x.i);
    }
    inline cpx operator -(const cpx&x)const{
        return cpx(r - x.r,i - x.i);
    }
}a[N],b[N];
int n,L,R[N],c[N];
char ch[N];
inline int read()
{
    int x = 0; char c;int sign = 1;
    do { c = getchar();if(c == '-') sign = -1; }while(c < '0' || c > '9');
    do { x = x*10 + c - '0';c = getchar(); }while(c <= '9' && c >= '0');
    x *= sign;
    return x;
}
inline void fft(cpx*a,int f)
{
    rep(i,0,n-1) if(i < R[i]) swap(a[i],a[R[i]]);
    for(register int i = 1;i < n;i <<= 1) {
        cpx wn(cos(pi/i),f*sin(pi/i));
        for(register int j = 0;j < n;j += (i<<1)) {
            cpx w(1,0);
            for(register int k = 0;k < i;++k,w *= wn) {
                cpx x = a[j + k],y = w * a[j + k + i];
                a[j + k] = x + y; a[j + k + i] = x - y;
            }
        }
    }
    if(f == -1) rep(i,0,n - 1) a[i].r /= n;
}
int main()
{
    n = read();n--;
    scanf("%s",ch);
    rep(i,0,n) a[i].r = ch[n-i] - '0';
    scanf("%s",ch);
    rep(i,0,n) b[i].r = ch[n-i] - '0';
    int m = 2*n; for(n = 1;n <= m ;n <<= 1) ++L;
    rep(i,0,n-1) R[i] = (R[i>>1]>>1)|((i&1)<<(L-1));
    fft(a,1);fft(b,1);
    rep(i,0,n) a[i] *= b[i];
    fft(a,-1);
    rep(i,0,m) c[i] = (int)(a[i].r + 0.1);
    rep(i,0,m)
        if(c[i] >= 10)
        {
            c[i+1] += c[i] / 10,c[i] %= 10;
            if(i == m) m++;
        }
    while(m) if(c[m]) break; else m--;
    while(~m) printf("%d",c[m--]);
    return 0;
}

 

posted @ 2017-10-18 16:59  DDYYZZ  阅读(901)  评论(0编辑  收藏  举报