N-----为信号f(n)的长度
s(n)----为卷积结果序列,长度为len(f(n))+len(g(n))-1
以3个元素的信号为例:
f(n) = [1 2 3]; g(n) = [2 3 1];
s(0) = f(0)g(0-0) + f(1)g(0-1)+f(2)g(0-2) = 1*2 + 2*0 + 3*0 =2
s(1) = f(0)g(1-0) + f(1)g(1-1) + f(2)g(1-2) = 1*3 + 2*2 + 3*0 = 7
s(2) = f(0)g(2-0) + f(1)g(2-1) + f(2)g(2-2) =1*1 + 2*3 + 3*2=13
s(3) = f(0)g(3-0) + f(1)g(3-1) + f(2)g(3-2) =1*0 + 2*1 + 3*3=11
s(4) = f(0)g(4-0) + f(1)g(4-1) + f(2)g(4-2) =1*0 + 2*0 + 3*1=3
最终结果为:
扫描二维码关注公众号,回复:
5549690 查看本文章
s(n) = [2 7 13 11 3]
以上摘自https://www.cnblogs.com/wujing-hubei/p/5682766.html
如果把它想成多项式,则f(x)=1+2x+3x^2 g(x)=2+3x+x^2
则f(x)乘g(x)的系数就是s(n),结果为2+7x+13x^2+11x^3+3x^4
所以多项式相乘可以这么做,即直接求f(n)和g(n)系数的卷积
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 50002
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
//复数结构体
struct complex
{
double r,i;
complex(double _r = 0,double _i = 0)
{
r = _r; i = _i;
}
complex operator +(const complex &b)
{
return complex(r+b.r,i+b.i);
}
complex operator -(const complex &b)
{
return complex(r-b.r,i-b.i);
}
complex operator *(const complex &b)
{
return complex(r*b.r-i*b.i,r*b.i+i*b.r);
}
};
void change(complex y[],int len)
{
int i,j,k;
for(i = 1, j = len/2;i < len-1;i++)
{
if(i < j)swap(y[i],y[j]);
k = len/2;
while( j >= k)
{
j -= k;
k /= 2;
}
if(j < k)j += k;
}
}
void fft(complex y[],int len,int on)
{
change(y,len);
for(int h = 2;h <= len;h <<= 1)
{
complex wn(cos(-on*2*PI/h),sin(-on*2*PI/h));
for(int j = 0;j < len;j += h)
{
complex w(1,0);
for(int k = j;k < j+h/2;k++)
{
complex u = y[k];
complex t = w*y[k+h/2];
y[k] = u+t;
y[k+h/2] = u-t;
w = w*wn;
}
}
}
if(on == -1)
for(int i = 0;i < len;i++)
y[i].r /= len;
}
int num[N*4];
char s1[N],s2[N];
complex p2[N*4],p1[N*4];
int main()
{
freopen("t.txt","r",stdin);
while(scanf("%s",s1)!=EOF)
{
scanf("%s",s2);
int l1=0,l2=0,la=strlen(s1),lb=strlen(s2);
while((1<<l1)<la) l1++;
while((1<<l2)<lb) l2++;
int l=1<<(max(l1,l2)+1);
for(int i=0;i<l;i++)
{
if(i<la) p1[i]=complex(s1[la-1-i]-'0',0);
else p1[i]=complex(0,0);
if(i<lb) p2[i]=complex(s2[lb-1-i]-'0',0);
else p2[i]=complex(0,0);
}
fft(p1,l,1);fft(p2,l,1);
for(int i=0;i<l;i++)
p1[i]=p1[i]*p2[i];
fft(p1,l,-1);
for(int i=0;i<l;i++)
{
num[i]=(int)(p1[i].r+0.5);
}
for(int i=0;i<l-1;i++)
{
num[i+1]+=num[i]/10;
num[i]%=10;
}
bool fg=true;
for(int i=l-1;i>=0;i--)
{
if(num[i]!=0&&fg)
{
fg=false;
}
if(!fg)
{
printf("%d",num[i]);
}
}
if(fg) printf("0");
printf("\n");
}
return 0;
}