# BZOJ 2194: 快速傅立叶之二(fft)

Description

Input

Output

Sample Input
5

3 1

2 4

1 1

2 4

1 4
Sample Output
24

12

10

6

1

## 解题思路

$fft$模板题，首先发现原式中$b$$a$相减是一个定值。所以要翻转一下变成和为定值。原式化简为$c_k=\sum\limits_{i=k}^{n-1}a_{i}*b_{n-i-1+k}=d_{n+k-1}$，这样就可以直接算了。

## 代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>

using namespace std;
const int MAXN = 800005;
const double Pi = acos(-1);

inline int rd(){
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)) {f=ch=='-'?0:1;ch=getchar();}
while(isdigit(ch))  {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return f?x:-x;
}

int n,limit=1,rev[MAXN<<3];

struct Complex{
double x,y;
Complex(double xx=0,double yy=0) {
x=xx;y=yy;
}
}a[MAXN],b[MAXN];

Complex operator +(const Complex A,const Complex B){return Complex(A.x+B.x,A.y+B.y);}
Complex operator -(const Complex A,const Complex B){return Complex(A.x-B.x,A.y-B.y);}
Complex operator *(const Complex A,const Complex B){return Complex(A.x*B.x-A.y*B.y,A.x*B.y+A.y*B.x);}

inline void fft(Complex *f,int type){
for(int i=0;i<limit;i++)
if(i<rev[i]) swap(f[i],f[rev[i]]);
Complex Wn,w,tmp;int len;
for(int p=2;p<=limit;p<<=1){
len=p>>1;Wn=Complex(cos(Pi/len),type*sin(Pi/len));
for(int k=0;k<limit;k+=p){
w=Complex(1,0);
for(int l=k;l<k+len;l++){
tmp=w*f[l+len];f[l+len]=f[l]-tmp;
f[l]=f[l]+tmp;w=w*Wn;
}
}
}
}

int main(){
n=rd();n--;
for(int i=0;i<=n;i++) {a[i].x=rd();b[n-i].x=rd();}
while(limit<=2*n) limit<<=1;
for(int i=0;i<limit;i++) rev[i]=((rev[i>>1]>>1)|((i&1)?limit>>1:0));
fft(a,1);fft(b,1);
for(int i=0;i<limit;i++) a[i]=a[i]*b[i];
fft(a,-1);
for(int i=0;i<=n;i++) printf("%d\n",(int)(a[n+i-1].x/limit+0.5));
return 0;
}

posted @ 2018-11-26 15:56  Monster_Qi  阅读(145)  评论(0编辑  收藏  举报