题解 P3803 【【模板】多项式乘法(FFT)】

· · 题解

P党福利!

如果要学FFT的话请右转我的blog。

不过,由于这题数据范围大,如果手写complex用FFT的话会爆栈,然后会RE。

所以只能用NTT了。

另外,由于Pascal的mod效率是真的低,这题需要卡常过。

尝试了各种方法才卡过去的

具体会在代码里写如何卡常。

type
  arr=array[0..2097151]of longint;
const
  p=998244353;
  g=3;
  gi=332748118;
var
  a,b,pow,r:arr;
  n,m,i,num,l,inv:longint;
function power(x,y:longint):longint;
begin
  power:=1;
  while y>0 do
  begin
    if odd(y) then
      power:=int64(power)*x mod p;//所有的乘法运算都需要强制类型转换(不然会溢出)
    x:=sqr(int64(x)) mod p;    //跑的慢没办法(如果dalao有兴趣探究可以把所有变量改成int64)
    y:=y shr 1;                //能用位运算就用位运算
  end;
end;
procedure ntt(var a:arr;n,s:longint);
var
  i,j,k,x,y,w:longint;
begin
  for i:=0 to n-1 do
    if i<r[i] then
    begin
      a[i]:=a[i] xor a[r[i]];  //位运算交换
      a[r[i]]:=a[i] xor a[r[i]];
      a[i]:=a[i] xor a[r[i]];
    end;
  i:=1;
  while i<n do
  begin
    j:=0;
    if s=1 then
      w:=power(g,(p-1) div (i shl 1))
    else
      w:=power(gi,(p-1) div (i shl 1));
    pow[0]:=1;
    for k:=1 to i-1 do         //把wnk存下来,减少运算次数
      pow[k]:=int64(pow[k-1])*w mod p;
    while j<n do
    begin
      for k:=0 to i-1 do
      begin
        x:=a[j+k];
        y:=int64(a[i+j+k])*pow[k] mod p;
        a[j+k]:=(x+y) mod p;
        a[i+j+k]:=(x-y) mod p;
      end;
      inc(j,i shl 1);
    end;
    i:=i shl 1;
  end;
end;
begin
  read(n,m);
  for i:=0 to n do             //读入不解释
    read(a[i]);
  for i:=0 to m do
    read(b[i]);
  num:=1;
  l:=0;
  while num<=n+m do            //计算长度
  begin
    num:=num shl 1;
    inc(l);
  end;
  for i:=0 to num-1 do         //递推顺序
    r[i]:=(r[i shr 1] shr 1) or ((i and 1) shl (l-1));
  //这里没有选择预处理所有的wnk
  //我们知道由于n取的是1,2,4,8
  //可以提前计算出当n最大时的wnk,然后计算下标就行了
  //但是通过试验发现,这样反而会TLE
  //所以为了卡常还是每次单独计算wnk了
  ntt(a,num,1);
  ntt(b,num,1);
  for i:=0 to num-1 do         //卷积
    a[i]:=int64(a[i])*b[i] mod p;
  ntt(a,num,-1);
  inv:=power(num,p-2);
  for i:=0 to n+m do
    a[i]:=(int64(a[i])*inv mod p+p) mod p;//防止负数导致一些奇怪的结果,毕竟Pascal的取模不一样
  for i:=0 to n+m do
    write(a[i],' ');
  writeln;
end.

感觉这种题目都没有人用Pascal做了呢……