模板——快速傅里叶变换(递归)

#include<cmath>
#include<iostream>
using namespace std;

const int N = 1e6 + 10;
const double PI = acos(-1);

struct Complex
{
	double R, I;
	Complex() { R = 0, I = 0; }
	Complex(double r, double i) :R(r), I(i) {}
};
Complex operator+(Complex a, Complex b) { return Complex(a.R + b.R, a.I + b.I); }
Complex operator-(Complex a, Complex b) { return Complex(a.R - b.R, a.I - b.I); }
Complex operator*(Complex a, Complex b) { return Complex(a.R * b.R - a.I * b.I, a.R * b.I + a.I * b.R); }


void FFT(Complex* a, int lim, int op) {
	if (lim == 1) return;
	Complex* a0 = new Complex[lim + 1];
	Complex* a1 = new Complex[lim + 1];
	for (int i = 0; i < lim; i += 2) {
		a0[i >> 1] = a[i];
		a1[i >> 1] = a[i + 1];
	}
	FFT(a0, lim >> 1, op);
	FFT(a1, lim >> 1, op);
	Complex wn = Complex(cos(2.0 * PI / lim), op * sin(2.0 * PI / lim));
	Complex w = Complex(1, 0);
	int mid = lim >> 1;
	for (int i = 0; i < mid; i++) {
		Complex t = w * a1[i];
		a[i] = a0[i] + t;
		a[i + mid] = a0[i] - t;
		w = w * wn;
	}

	delete[]a0, a0 = NULL;
	delete[]a1, a1 = NULL;
}

Complex F[N], G[N];
int main() {

	int n, m;
	cin >> n >> m;

	for (int i = 0; i <= n; i++) cin >> F[i].R;
	for (int i = 0; i <= m; i++) cin >> G[i].R;
	int k = 1;
	while (k <= n + m) k <<= 1;
	FFT(F, k, 1);
	FFT(G, k, 1);
	for (int i = 0; i <= k; i++) {
		F[i] = F[i] * G[i];
	}
	FFT(F, k, -1);
	for (int i = 0; i <= n + m; i++) {
		cout << (int)(F[i].R / k + 0.5) << " ";
	}

	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值