FFT模板(BZOJ2179)

实现了两个长度为n的大数相乘。

#include <cstdio>
#include <cmath>
#include <complex>
using namespace std;
#define pi acos(-1)

typedef complex<double> C;
const int N = 131100;
char s[N],t[N];
int n,m,l,r[N],c[N];
C a[N],b[N];

void fft(C *a, int f) {
    for(int i = 0; i < n; i++) if(r[i] > i) swap(a[i], a[r[i]]);
    for(int i = 1; i < n; i <<= 1) {
        C wn(cos(pi/i), f*sin(pi/i));
        for(int j = 0; j < n; j += i<<1) {
            C w = 1;
            for(int k = 0; k < i; k++, w *= wn) {
                C x = a[j+k], y = w*a[j+k+i];
                a[j+k] = x+y, a[j+k+i] = x-y;
            }
        }
    }
}

int main() {
    scanf("%d%s%s", &m, s, t);
    for(int i = 0; i < m; i++) a[i] = s[m-i-1]-'0', b[i] = t[m-i-1]-'0';
    for(n = 1, m <<= 1; n < m; n <<= 1) l++;
    for(int i = 0; i < n; i++) r[i] = (r[i>>1]>>1)|((i&1)<<(l-1));
    fft(a, 1), fft(b, 1);
    for(int i = 0; i < n; i++) a[i] *= b[i];
    fft(a, -1);
    for(int i = 0; i < n; i++) a[i] /= n;
    for(int i = 0; i < m; i++) c[i] = (int)(a[i].real()+0.1);
    for(int i = 0; i < m; i++) if(c[i] >= 10) {
        c[i+1] += c[i]/10, c[i] %= 10;
    } else if(!c[i] && i == m-1) m--;
    for(int i = m-1; ~i; i--) printf("%d", c[i]);
    return 0;
}
posted @ 2016-12-14 19:34  Monster_Yi  阅读(752)  评论(0编辑  收藏  举报