Luogu3803 [template] polynomial multiplication (FFT)

In fact, quite FFT water, add a little careful mathematical foundation can be. · Skills with a lot of details.
Konjac I can not even open the arrays are much

Recursion

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

//#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 4000007; // how much should I open QAQ ?
const double pi = acos(-1.0);

struct Complex{
    double x, y;
    Complex (double xx = 0, double yy = 0) {x = xx, y = yy;}
    
    Complex operator + (Complex b){ return Complex(x + b.x, y + b.y); }
    Complex operator - (Complex b){ return Complex(x - b.x, y - b.y); }
    Complex operator * (Complex b){ return Complex(x * b.x - y * b.y, x * b.y + y * b.x); } 
}a[N], b[N];

inline void FFT(int limit, Complex *a, int opt){
    if(limit == 1) return;
    Complex a1[(limit >> 1) + 3], a2[(limit >> 1) + 3];
    for(register int i = 0; i <= limit; i += 2){
        a1[i >> 1] = a[i];
        a2[i >> 1] = a[i + 1];
    }
    FFT(limit >> 1, a1, opt);
    FFT(limit >> 1, a2, opt);
    Complex Wn = Complex( cos(2.0 * pi / limit), opt * sin(2.0 * pi / limit));
    Complex w = Complex( 1, 0);
    R(i,0,(limit >> 1) - 1){ // be careful, do not write 'R(i,0,(limit >> 1))'
        a[i] = a1[i] + w * a2[i];
        a[i + (limit >> 1)] = a1[i] - w * a2[i];
        w = w * Wn;
    }
}

int main(){
    int n, m;
    io >> n >> m;
    R(i,0,n) io >> a[i].x;
    R(i,0,m) io >> b[i].x;

    int limit;
    for(limit = 1; limit <= n + m; limit <<= 1);
    
    FFT(limit, a, 1);
    FFT(limit, b, 1); // coefficient changes to point value
    
    R(i,0,limit){
        a[i] = a[i] * b[i];
    }
    
    FFT(limit, a, -1); // point value changes to coefficient
    
    R(i,0,n + m){
        printf("%d ", (int)(a[i].x / limit + 0.5)); // ans should divide limit
    }
    
    return 0;
}

Guess you like

Origin www.cnblogs.com/bingoyes/p/11225225.html