给一个集合,用这个集合组成的长度为n的序列中,在mod m下乘积为x的个数。n <= 10^9, m <= 8000。m是质数
首先可以把乘积变为原根的指数相加的形式,然后取模FFT即可。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#define Rep(i, x, y) for (int i = x; i <= y; i ++)
#define Dwn(i, x, y) for (int i = x; i >= y; i --)
#define RepE(i, x) for(int i = pos[x]; i; i = g[i].nex)
using namespace std;
typedef long long LL;
const int P = 1004535809, M = 18000;
int n, m, X, S, mx[M], N; LL a[M], w[2][M], inv_N, b[M], d[M], mg = 2;
LL Pow(LL x, int y, int mod = P) {
LL z = 1;
while (y) {
if (y & 1) (z *= x) %= mod;
(x *= x) %= mod, y >>= 1;
}
return z;
}
void FFT_Init() {
for (N = 1; N < m; N <<= 1); N <<= 1; inv_N = Pow(N, P - 2);
int G = Pow(3, (P - 1) / N);
w[0][0] = w[1][0] = w[0][N] = w[1][N] = 1;
Rep(i, 1, N - 1) {
w[0][i] = w[1][N - i] = w[0][i - 1] * G % P;
}
}
bool Check(int g, int m) {
for (int i = 2; i * i < m; i ++)
if ((m - 1) % i == 0 && (Pow(g, i, m) == 1 || Pow(g, (m - 1) / i, m) == 1)) return 0;
return 1;
}
void FFT(LL *a, int n, int f) {
for (int i = n >> 1, j = 1, k; j < n - 1; j ++) {
if (j < i) swap(a[i], a[j]);
for (k = n >> 1; k <= i; k >>= 1) i ^= k;
i ^= k;
}
for (int i = 2; i <= n; i <<= 1) {
for (int j = 0; j < n; j += i) {
Rep(k, 0, i / 2 - 1) {
LL x = a[j + k], y = a[j + k + i / 2] * w[f][k * (n / i)] % P;
a[j + k] = (x + y) % P, a[j + k + i / 2] = (x - y + P) % P;
}
}
}
if (f) Rep(i, 0, n - 1) a[i] = a[i] * inv_N % P;
}
void Work(LL *a, LL *b) {
Rep(i, 0, N - 1) d[i] = b[i];
FFT(a, N, 0), FFT(d, N, 0);
Rep(i, 0, N - 1) a[i] = a[i] * d[i] % P;
FFT(a, N, 1);
Dwn(i, N - 1, m - 1) (a[i - m + 1] += a[i]) %= P, a[i] = 0;
}
int main()
{
scanf ("%d%d%d%d", &n, &m, &X, &S);
while (!Check(mg, m)) mg ++;
int m0 = 1; mx[1] = 0;
Rep(i, 1, m - 2) m0 = m0 * mg % m, mx[m0] = i;
FFT_Init();
Rep(i, 1, S) {
int x; scanf ("%d", &x);
if (x) a[ mx[x] ] = 1;
}
b[0] = 1;
while (n) {
if (n & 1) Work(b, a);
Work(a, a), n >>= 1;
}
printf("%lld\n", b[ mx[X] ]);
return 0;
}