Luogu4512 【模板】多项式除法
Luogu4512 【模板】多项式除法
\(NTT\)
\[F(x)=Q(x) \times G(x) + R(x)
\]
对于一个\(n\)次多项式\(f(x)=\sum_{i=0}^n a_i x^i\),定义\(f^r(x)=\sum_{i=0}^n a_{n-i} x^i\)。
\[F(\frac{1}{x})=Q(\frac{1}{x}) \times G(\frac{1}{x}) + R(\frac{1}{x})\\
x^n F(\frac{1}{x})=x^n (Q(\frac{1}{x}) \times G(\frac{1}{x}) + R(\frac{1}{x}))\\
F^r(x)=Q^r(x)G^r(x)+x^{n-m+1}R^r(x)\\
F^r(x)=Q^r(x)G^r(x) \mod(x^{n-m+1})\\
Q^r(x)=\frac{F^r(x)}{G^r(x)} \mod(x^{n-m+1}) \\
R(x)=F(x)-G(x)Q(x)
\]
\(Code:\)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 400005
#define ll long long
using namespace std;
const int p=998244353;
int n,m,f[N],g[N],F[N],G[N],Q[N],R[N],c[N],d[N];
int s,l,E[2][35],rev[N];
void Add(int &x,int y)
{
x=(x+y>=p)?(x+y-p):(x+y);
}
void Del(int &x,int y)
{
x=(x>=y)?(x-y):(x-y+p);
}
void Mul(int &x,int y)
{
x=(ll)x*y%p;
}
int add(int x,int y)
{
return (x+y>=p)?(x+y-p):(x+y);
}
int del(int x,int y)
{
return (x>=y)?(x-y):(x-y+p);
}
int mul(int x,int y)
{
return (ll)x*y%p;
}
int ksm(int x,int y)
{
int ans(1);
while (y)
{
if (y & 1)
Mul(ans,x);
Mul(x,x);
y >>=1;
}
return ans;
}
void Pre()
{
E[0][23]=ksm(3,(p-1)/(1 << 23));
E[1][23]=ksm(E[0][23],p-2);
for (int i=22;i;--i)
{
E[0][i]=mul(E[0][i+1],E[0][i+1]);
E[1][i]=mul(E[1][i+1],E[1][i+1]);
}
}
void solve(int n)
{
s=1,l=0;
while (s<n)
s <<=1,++l;
for (int i=0;i<s;++i)
rev[i]=(rev[i >> 1] >> 1) | ((i & 1) << l-1);
}
void Cut(int *a,int n,int s)
{
if (n>s)
return;
memset(a+n,0,(s-n)*sizeof(int));
}
void NTT(int *a,int t)
{
for (int i=0;i<s;++i)
if (i<rev[i])
swap(a[i],a[rev[i]]);
for (int mid=1,o=1;mid<s;mid <<=1,++o)
for (int j=0;j<s;j+=(mid << 1))
{
int g(1);
for (int k=0;k<mid;++k,Mul(g,E[t][o]))
{
int x(a[j+k]),y(mul(g,a[j+k+mid]));
a[j+k]=add(x,y),a[j+k+mid]=del(x,y);
}
}
}
void GetInv(int *f,int *g,int R)
{
if (R==2)
{
g[0]=ksm(f[0],p-2);
return;
}
GetInv(f,g,R >> 1);
memcpy(c,g,(R >> 2)*sizeof(int)),memcpy(d,f,(R >> 1)*sizeof(int));
solve(R),NTT(c,0),NTT(d,0);
for (int i=0;i<s;++i)
c[i]=del(add(c[i],c[i]),mul(d[i],mul(c[i],c[i])));
NTT(c,1);
int iv(ksm(s,p-2));
for (int i=0;i<s;++i)
Mul(c[i],iv);
memcpy(g,c,(R >> 1)*sizeof(int)),memset(c,0,s*sizeof(int)),memset(d,0,s*sizeof(int));
}
int main()
{
Pre();
scanf("%d%d",&n,&m);
for (int i=0;i<=n;++i)
scanf("%d",&f[i]);
for (int i=0;i<=m;++i)
scanf("%d",&g[i]);
for (int i=0;i<=n;++i)
F[i]=f[n-i];
for (int i=0;i<=m;++i)
G[i]=g[m-i];
Cut(F,n-m+1,n+1);
Cut(G,n-m+1,m+1);
s=1;
while (s<n-m+1)
s <<=1;
s <<=1;
GetInv(G,Q,s);
Cut(Q,n-m+1,s);
solve((n-m+1) << 1);
NTT(Q,0),NTT(F,0);
for (int i=0;i<s;++i)
Mul(Q[i],F[i]);
NTT(Q,1);
int iv(ksm(s,p-2));
for (int i=0;i<s;++i)
Mul(Q[i],iv);
Cut(Q,n-m+1,s);
reverse(Q,Q+n-m+1);
for (int i=0;i<n-m+1;++i)
printf("%d ",Q[i]);
putchar('\n');
solve(n-m+1+m+1);
NTT(Q,0),NTT(g,0);
for (int i=0;i<s;++i)
Mul(Q[i],g[i]);
NTT(Q,1);
iv=ksm(s,p-2);
for (int i=0;i<s;++i)
Mul(Q[i],iv);
for (int i=0;i<n;++i)
Del(f[i],Q[i]);
for (int i=0;i<m;++i)
printf("%d ",f[i]);
putchar('\n');
return 0;
}