A*B problem

· · 个人记录

#include<bits/stdc++.h>
#define pre(i, l, r)    for(int i = (l); i <= (r); ++i)
#define fpre(i, r, l)   for(int i = (r); i >= (l); --i)
#define ll long long

using namespace std;

const int maxn = 2e5 + 5;

int n, m, r[maxn], l = 1;
string s1, s2;
complex<double> a[maxn], b[maxn];
double p = acos(-1);

inline void FFT(complex<double> a[], int x, int f)
{
    pre(i, 0, x - 1)
    {
        r[i] = (r[i >> 1] >> 1);
        if(i & 1)   r[i] |= (x >> 1);
        if(i < r[i])    swap(a[i], a[r[i]]);
    }
    for(int g = 2; g <= x; g <<= 1)
    {
        complex<double> wn(cos(p * 2 / g), f * sin(p * 2 / g));
        for(int i = 0; i < x; i += g)
        {
            complex<double> w(1, 0);
            for(int j = i; j < i + g / 2; j++, w *= wn)
            {
                complex<double> l = a[j], r = a[j + g / 2];
                a[j] = l + w * r;
                a[j + g / 2] = l - w * r;
            }
        }
    }
    if(f == -1)
        pre(i, 0, x - 1)
            a[i] /= x;
}

int main()
{
    cin >> s1 >> s2;
    n = s1.size(), m = s2.size();
    pre(i, 0, n - 1)
        a[n - i - 1] = (double)(s1[i] ^ 48);
    pre(i, 0, m - 1)
        b[m - i - 1] = (double)(s2[i] ^ 48);
    while(l < n + m)    l <<= 1;
    FFT(a, l, 1), FFT(b, l, 1);
    pre(i, 0, l - 1)    a[i] *= b[i];
    FFT(a, l, -1);
    pre(i, 0, l - 1)
        a[i + 1] += (int)(a[i].real() + 0.5) / 10;
    while((int)(a[l].real() + 0.5) <= 0)    --l;
    if(!l)  return puts("0") & 0;
    fpre(i, l, 0)
        printf("%d", (int)(a[i].real() + 0.5) % 10);
    puts("");
    return 0;
}