BZOJ-2194 快速傅立叶之二

FFT模版题。

观察题目,我们可以发现,只要把序列b倒过来,再联想一下乘法运算。。。

我们会发现,将序列a和序列b当作100进制数,做一次乘法,然后从低到高每一位便是答案了(乘完无需进位)

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <complex>
#define rep(i, l, r) for(int i=l; i<=r; i++)
#define down(i, l, r) for(int i=l; i>=r; i--)
#define maxn 400009
#define cd complex <double>
#define PI acos(0.0)*2.0
#define ll long long
using namespace std;
inline int read()
{
	int x=0, f=1; char ch=getchar();
	while (!isdigit(ch)) {if (ch=='-') f=-1; ch=getchar();}
	while (isdigit(ch)) x=x*10+ch-'0', ch=getchar();
	return x*f;
}
cd a[maxn], b[maxn], c[maxn], A[maxn];
int n, m, n1[maxn], n2[maxn], s[maxn];
int ans[maxn];

void fft(cd *a, bool flag)
{
	rep(i, 0, n-1) s[i]=0;
	for(int i=1, j=n; i<n; i*=2, j/=2) rep(h, j/2, j-1) s[h]+=i;
	for(int i=1; i<n; i*=2) rep(j, 0, i-1) s[j+i]+=s[j];
	rep(i, 0, n-1) A[i]=a[s[i]];
	double pi=flag?PI:-PI;
	for(int step=1; step<n; step*=2)
	{
		cd e=exp(cd(0, 2.0*pi/double(step*2))), w=cd(1, 0);
		for (int pos=0; pos<step; pos++, w*=e) 
			for(int i=pos; i<n; i+=step*2)
			{
				cd ret=A[i], rec=w*A[i+step];
				A[i]=ret+rec, A[i+step]=ret-rec;
			}
	}
	if (!flag) rep(i, 0, n-1) A[i]/=n;
	rep(i, 0, n-1) a[i]=A[i];
}

int main()
{
	m=read(); 
	rep(i, 1, m) n1[m-i]=read(), n2[i-1]=read();
	n=1; while (n<m*2) n*=2;
	rep(i, 0, n-1) a[i]=cd(n1[i], 0); fft(a, true);
	rep(i, 0, n-1) b[i]=cd(n2[i], 0); fft(b, true);
	rep(i, 0, n-1) c[i]=a[i]*b[i]; fft(c, false);
	rep(i, 0, m-1) ans[i]=c[i].real()+0.5;
	down(i, m-1, 0) printf("%d\n", ans[i]);
}
posted @ 2015-05-05 16:07  NanoApe  阅读(184)  评论(0编辑  收藏  举报
AmazingCounters.com