COGS 1473 O(N*logN) 高精乘 FFT

题意: 求A*B, A <= 10^150000

万进制亿进制走吧,放弃吧...

正解fft 模板么,随便搞搞就好了...

 

#include <iostream>
#include <cstring>
#include <algorithm>
#include <stdio.h>
#include <math.h>
using std::swap;
#define MAXN 530010
const double PI = acos(-1.0);
char s1[MAXN],s2[MAXN];
int rev[MAXN],N,len,len1,len2,cnt,Ans[MAXN];
  
  
template<typename _t>
inline _t read(){
    _t x=0,f=1;
    char ch=getchar();
    for(;ch>'9'||ch<'0';ch=getchar())if(ch=='-')f=-f;
    for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+(ch^48);
    return x*f;
}
  
struct Complex{
    double x,y;
    inline Complex operator + (const Complex & a){return (Complex){x+a.x,y+a.y};}
    inline Complex operator - (const Complex & a){return (Complex){x-a.x,y-a.y};}
    inline Complex operator * (const Complex & a){return (Complex){x*a.x-y*a.y,x*a.y+y*a.x};}
}a[MAXN],b[MAXN],c[MAXN];
  
inline void fft(Complex *a,int type){
    Complex wn,w,t;
    for(int i=0;i<N;i++)if(i<rev[i])swap(a[i],a[rev[i]]);
    for(int k=2;k<=N;k<<=1){
        wn = (Complex){cos(type*2*PI/k),sin(type*PI*2/k)};
        for(int j=0;j<N;j+=k){
            w = (Complex){1,0};
            for(int i=0;i<(k>>1);i++,w=w*wn)
                t=a[i+j+(k>>1)]*w,a[i+j+(k>>1)]=a[i+j]-t,a[i+j]=a[i+j]+t;
        }
    }
    if(type==-1) for(int i=0;i<N;i++) a[i].x/=N;
}
  
void FFT(Complex *a,Complex *b,int *Ans,int tot){
    for(N=1;N<(tot<<1);len++,N<<=1);
    for(int i=0;i<N;i++) {
        if(i&1)rev[i]=(rev[i>>1]>>1)|(N>>1);
        else rev[i]=rev[i>>1]>>1;
    }
    fft(a,1);fft(b,1);
    for(int i=0;i<N;i++) c[i]=a[i]*b[i];fft(c,-1);
    for(int i=0;i<N;i++) Ans[i]=round(c[i].x);
}
  
int main(){
    scanf("%s%s",s1,s2);
    len1=strlen(s1);len2=strlen(s2);
    cnt = len1>len2?len1:len2;
    for(int i=0;i<len1;i++)a[i].x=s1[len1-i-1]-48;
    for(int i=0;i<len2;i++)b[i].x=s2[len2-i-1]-48;
    FFT(a,b,Ans,cnt);
    for(int i=0;i<N;i++) {
        Ans[i+1] += Ans[i] / 10;
        Ans[i] %= 10;
    }
    len = len1+len2;
    while(!Ans[len]&&len>=1)--len;
    for(int i=len;i>=0;i--)printf("%c",Ans[i]+'0');
}


 

posted @ 2017-08-14 21:13  cooook  阅读(239)  评论(0编辑  收藏  举报