2179: FFT快速傅立叶
Time Limit: 10 Sec Memory Limit: 259 MBSubmit: 4214 Solved: 2259
[ Submit][ Status][ Discuss]
Description
给出两个n位10进制整数x和y,你需要计算x*y。
Input
第一行一个正整数n。 第二行描述一个位数为n的正整数x。 第三行描述一个位数为n的正整数y。
Output
输出一行,即x*y的结果。
Sample Input
1
3
4
3
4
Sample Output
12
数据范围:
n<=60000
数据范围:
n<=60000
HINT
Source
NTT模板
不想解释了。。。直接上代码
代码:
#include<cstdio>
#include<vector>
#include<queue>
#include<ctime>
#include<algorithm>
#include<cstdlib>
#include<stack>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long LL;
typedef double DL;
const int INF = 2147483647;
const int maxn = 300100;
const LL crz = 479 * (1 << 21) + 1;
LL a[maxn],p[maxn],b[maxn],tmp[maxn];
int n,m,len;
int rev[maxn],dig[25];
LL ans[maxn],wn[maxn];
inline LL getint()
{
LL ret = 0,f = 1;
char c = getchar();
while (c < '0' || c > '9')
{
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
ret = ret * 10 + c - '0',c = getchar();
return ret * f;
}
inline LL qpow(LL a,LL b)
{
a %= crz;
LL ret = 1;
while (b)
{
if (b & 1) ret = (ret * a) % crz;
a = (a * a) % crz;
b >>= 1;
}
return ret;
}
inline void NTT(LL *a,int on)
{
memset(tmp,0,sizeof(tmp));
for (int i = 0; i < len; i++) tmp[i] = a[rev[i]];
for (int i = 0; i < len; i++) a[i] = tmp[i];
int id = 1;
for (int h = 2; h <= len; h <<= 1 , id++)
for (int i = 0; i < len; i += h)
{
LL w = 1;
for (int j = i; j <= i + h / 2 - 1; j++)
{
LL u = a[j],t = w * a[j + h / 2] % crz;
a[j] = (u + t) % crz;
a[j + h / 2] = (u - t + crz) % crz;
w = (w * wn[id]) % crz;
}
}
if (on == -1)
{
for(int i = 1; i < len / 2; i++)
swap(a[i], a[len - i]);
LL inv = qpow(len,crz - 2);
for (int i = 0; i < len; i++)
a[i] = (a[i] * inv) % crz;
}
}
inline int getcom()
{
char c = getchar();
while (c < '0' || c > '9') c = getchar();
return c - '0';
}
inline void init()
{
for (len = 1; len <= n; len <<= 1 , m++);
len <<= 1; m++;
for (int i = 0; i < len; i++)
{
int p = -1;
memset(dig,0,sizeof(dig));
for (int x = i; x; x >>= 1) dig[++p] = x & 1;
for (int j = 0; j < m; j++)
rev[i] = (rev[i] << 1) + dig[j];
}
for (int i = 1; i <= m; i++) wn[i] = qpow(3,(crz - 1) / (1 << i));
}
int main()
{
n = getint(); init();
for (int i = 0; i < n; i++) a[i] = getcom();
for (int i = 0; i < n; i++) b[i] = getcom();
NTT(a,1);
NTT(b,1);
for (int i = 0; i < len; i++) p[i] = (a[i] * b[i]) % crz;
NTT(p,-1);
for (int i = 0; i < 2 * n - 1; i++) ans[i] = p[2 * n - 1 - i - 1];
int tot = -1;
while (tot < 2 * n - 2 || ans[tot + 1])
{
tot++;
ans[tot + 1] += ans[tot] / 10;
ans[tot] = ans[tot] % 10;
}
for (int i = tot; i >= 0; i--) putchar(ans[i] + '0');
return 0;
}