题目大意:给出两个n位10进制整数x和y,计算x*y。n<=60000
picks的博客对我有很大启发,里面写的很详细很明白,传送门Fast Fourier Transform
那么这道就是FFT裸题了。
板子在这里
#include <cstdio>
#include <cmath>
#define N 140000
using namespace std;
const double pi = acos(-1);
const double DFT = 2.0, IDFT = -2.0;
struct Complex {
double x, y;
Complex(const double& x = 0.0, const double& y = 0.0): x(x), y(y) {}
Complex operator + (const Complex& rhs) const { return Complex(x+rhs.x, y+rhs.y); }
Complex operator - (const Complex& rhs) const { return Complex(x-rhs.x, y-rhs.y); }
Complex operator * (const Complex& rhs) const { return Complex(x*rhs.x-y*rhs.y, x*rhs.y+y*rhs.x); }
}a[N], b[N], c[N];
inline void Swap(Complex& x, Complex& y) { Complex z = x; x = y; y = z; }
int n, len, pos[N];
int top, ans[N];
void init() {
len = 1;
while(len < (n<<1)) len <<= 1;
for(int i = 0; i < len; i++) {
pos[i] = pos[i>>1]>>1;
if(i & 1) pos[i] |= len>>1;
}
return ;
}
void read(Complex x[]) {
static char s[N];
scanf("%s", s);
for(int i = 0; i < n; i++) x[i].x = floor(s[i]-'0');
return ;
}
void FFT(Complex x[], double mode) {
for(int i = 0; i < len; i++)
if(i < pos[i])
Swap(x[i], x[pos[i]]);
for(int i = 2; i <= len; i <<= 1) {
int step = i>>1;
Complex wm(cos(2*pi/i), sin(mode*pi/i));
for(int j = 0; j < len; j += i) {
int limit = j+step;
Complex w(1,0);
for(int k = j; k < limit; k++) {
Complex y = x[k], z = w*x[k+step];
x[k] = y+z , x[k+step] = y-z;
w = w*wm;
}
}
}
if(mode == IDFT)
for(int i = 0; i < len; i++)
x[i].x /= len;
return ;
}
int main() {
scanf("%d", &n);
read(a); read(b);
init();
FFT(a, DFT); FFT(b, DFT);
for(int i = 0; i < len; i++) c[i] = a[i]*b[i];
FFT(c, IDFT);
for(int i = (n<<1)-2; ~i; i--) ans[top++] = floor(c[i].x+0.5);
for(int i = 0; i < top; i++) ans[i+1] += ans[i]/10 , ans[i] %= 10;
if(ans[top]) printf("%d", ans[top]);
for(int i = top-1; ~i; i--) printf("%d", ans[i]); printf("\n");
return 0;
}