【洛谷 P2553】 [AHOI2001]多项式乘法(FFT)

题目链接
简单处理一下输入,\(fft\)模板题。

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#define re register
using namespace std;
const int MAXN = 1000010;
const double PI = M_PI;
struct complex{
    double x, y;
    complex(double xx = 0, double yy = 0){ x = xx; y = yy; }
}a[MAXN], b[MAXN], *f;
inline complex operator + (complex a, complex b){
	return complex(a.x + b.x, a.y + b.y);
}
inline complex operator - (complex a, complex b){
	return complex(a.x - b.x, a.y - b.y);
}
inline complex operator * (complex a, complex b){
	return complex(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
inline int read(){
	re int s = 0, w = 1;
	re char ch = getchar();
	while(ch < '0' || ch > '9'){ ch = getchar(); if(ch == '-') w = -1; }
	while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); }
	return s * w;
}
int r[MAXN], n, m;
void FFT(complex *f, int mode){
	for(re int i = 0; i < n; ++i) if(i < r[i]) swap(f[i], f[r[i]]);
	for(re int p = 2; p <= n; p <<= 1){
	   re int len = p >> 1;
	   re complex tmp(cos(PI / len), mode * sin(PI / len));
	   for(re int l = 0; l < n; l += p){
	      re complex w(1, 0);
	      for(re int k = l; k < l + len; ++k){
	      	 re complex t = w * f[len + k];
	      	 f[len + k] = f[k] - t;
	      	 f[k] = f[k] + t;
	      	 w = w * tmp;
	      }
	   }
    }
}
inline double d(double x){
	if(fabs(x) < 1e-9) return 0;
	return x;
}
char s[MAXN];
int *len = &n, now, flag, tmp;
int main(){
	while(scanf("%s", s + 1) != EOF){
	int leng = strlen(s + 1); n = m = flag = 0; f = a; len = &n;
	for(int i = 1; i <= leng; ++i){
		if(s[i] >= '0' && s[i] <= '9') now = now * 10 + s[i] - '0';
		if(s[i] == '^'){ flag = 1; tmp = now; now = 0; }
		if(s[i] == '+' || s[i] == ')'){
		  if(flag) f[now].x = tmp, *len = max(*len, now); 
		  else f[0].x = now;
		  flag = now = tmp = 0;
	    }
	    if(s[i] == '*') f = b, len = &m;
	}
	for(m += n, n = 1; n <= m; n <<= 1);
	for(re int i = 1; i < n; ++i) r[i] = r[i >> 1] >> 1 | ((i & 1) * (n >> 1));
	FFT(a, 1); FFT(b, 1);
	for(re int i = 0; i < n; ++i) a[i] = a[i] * b[i];
	FFT(a, -1);
	for(int i = m; ~i; --i) 
	   if(a[i].x > 1e-9){
	   	  if(flag) printf("+");
	      printf("%.0f", a[i].x / n, i);
	      if(i) printf("a^%d", i);
	      flag = 1;
	   }
	printf("\n");
	for(int i = 0; i < n; ++i) a[i].x = a[i].y = b[i].x = b[i].y = 0;
    }
	return 0;
}
posted @ 2019-02-13 08:56  Qihoo360  阅读(232)  评论(0编辑  收藏  举报
You're powerful!