luogu[愚人节题目3]现代妖怪殖民地 NTT
U34272 [愚人节题目3]现代妖怪殖民地 fft
题目链接
https://www.luogu.org/problemnew/show/U34272
思路
虽然是个py题。
ntt(或者fft)模板题,可能稍不注意就会T
代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+7,mod=998244353;
int n,m,a[N],b[N],limit=1,l,r[N];
int q_pow(int a,int b) {
int ans=1;
while(b) {
if(b&1) ans=1LL*ans*a%mod;
a=1LL*a*a%mod;
b>>=1;
}
return ans;
}
void ntt(int *a,int type) {
for(int i=0;i<limit;++i)
if(i<r[i]) swap(a[i],a[r[i]]);
for(int mid=1;mid<limit;mid<<=1) {
int Wn=q_pow(3,(mod-1)/(mid<<1));
for(int i=0;i<limit;i+=(mid<<1)) {
for(int j=0,w=1;j<mid;++j,w=1LL*w*Wn%mod) {
int x=a[i+j],y=1LL*w*a[i+j+mid]%mod;
a[i+j]=(x+y)%mod;
a[i+j+mid]=(x+mod-y)%mod;
}
}
}
if(type==-1) {
reverse(&a[1],&a[limit]);
int down=q_pow(limit,mod-2);
for(int i=0;i<=limit;++i) a[i]=1LL*a[i]*down%mod;
}
}
void solve() {
limit=1,l=0,n=m=-1;
char s=getchar();
int flag=1;
while(s==' '||s=='\n') s=getchar();
if(s=='-') flag*=-1;
else a[++n]=s-'0';
for(s=getchar();s>='0'&&s<='9';s=getchar()) a[++n]=s-'0';
while(s==' '||s=='\n') s=getchar();
if(s=='-') flag*=-1;
else b[++m]=s-'0';
for(s=getchar();s>='0'&&s<='9';s=getchar()) b[++m]=s-'0';
reverse(a,a+n+1);
reverse(b,b+m+1);
if(flag==-1) printf("-");
while(limit<=n+m) limit<<=1,l++;
for(int i=0;i<=limit;++i)
r[i]=(r[i>>1]>>1)|((i&1)<<(l-1));
ntt(a,1),ntt(b,1);
for(int i=0;i<=limit;++i) a[i]=1LL*a[i]*b[i]%mod;
ntt(a,-1);
int len=limit;
for(int i=0;i<=limit;++i)
a[i+1]+=a[i]/10,a[i]%=10;
while(!a[limit]&&limit) limit--;
while(limit>=0) printf("%d",a[limit--]);
for(int i=0;i<=len;++i) a[i]=b[i]=0;
printf("\n");
}
int main() {
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}