【BZOJ 2179】 FFT快速傅立叶

思路:

FFT 的模板题,也是重要的用途之一,那就是 O(nlogn) 的高精度乘法。
可以吧一个十进制数写成一个高精度的形式:

x=i=0lenai×10i

所以可以直接用系数做 FFT

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

const double pi = acos(-1);
const int maxn = 60010*3;
int Bit, rx[maxn], res[maxn];

struct Com{
    double x, y;
    Com(double X = 0, double Y = 0){x = X, y = Y;}
    Com(const Com &t){x = t.x, y = t.y;}
    Com operator + (const Com &t)const{return Com(x+t.x, y+t.y);}
    Com operator - (const Com &t)const{return Com(x-t.x, y-t.y);}
    Com operator * (const Com &t)const{return Com(x*t.x-y*t.y, x*t.y+y*t.x);}
};

void fft(Com *A, int n, int f){
    if(rx[n-1] != n-1) for(int i = 0; i < n; i ++) rx[i] = (rx[i>>1]>>1) | ((i&1) << (Bit-1));
    for(int i = 0; i < n; i ++) if(i < rx[i]) swap(A[i], A[rx[i]]);
    for(int i = 1; i < n; i <<= 1){
        const Com Base(cos(pi/i), f*sin(pi/i));
        for(int j = 0; j < n; j += i << 1){
            Com mi(1, 0);
            for(int k = 0; k < i; k ++, mi = mi * Base){
                Com x = A[j+k], y = A[i+j+k] * mi;
                A[j+k] = x+y, A[i+j+k] = x-y;
            }
        }
    }
}

char c1[maxn], c2[maxn];
Com a[maxn], b[maxn];

int main(){
    int n, m;
    scanf("%d", &n), m = n;
    scanf("%s%s", c1, c2);
    n --, m --;
    for(int i = n; i >= 0; i --){
        a[n-i].x = c1[i] - '0';
        b[n-i].x = c2[i] - '0';
    }
    m += n;
    for(n = 1; n <= m; n <<= 1, Bit ++);
    fft(a, n, 1);
    fft(b, n, 1);
    for(int i = 0; i < n; i ++) a[i] = a[i] * b[i];
    fft(a, n, -1);
    for(int i = 0; i <= m; i ++) res[i] = int(a[i].x/n + 0.5);
    for(int i = 0; i <= m; i ++) res[i+1] += res[i] / 10, res[i] %= 10;
    m ++;
    while(res[m] / 10) res[m+1] += res[m] / 10, res[m] %= 10;
    while(m != 0 && res[m] == 0) m --;
    for(int i = m; i >= 0; i --) printf("%d", res[i]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值