题意:一共 n ∗ m + p − 1 n*m+p-1 n∗m+p−1 个数,连续 p p p 个数的乘积 m o d mod mod P P P 作为矩阵中一个元素。现在在矩阵中找出一条长度为 k k k 的路径,且路径上所有元素在 m o d mod mod k k k 的意义下均不同。问这样的路径有多少条?
思路:首先是求连续
p
p
p 个数的乘积
m
o
d
mod
mod
P
P
P,可以把这些数按照
p
p
p 个数为一组划分,对于一段连续
p
p
p 个数的乘积即为其所覆盖的上一组的后缀积与所覆盖的这一组的前缀积的乘积。此复杂度为线性。
其次求长度为
k
k
k 的路径,由于
k
k
k 不大于20,可以通过双向
d
f
s
dfs
dfs ,枚举路径的中心点,选择路径上,通过状态压缩来处理,时间复杂度为
n
∗
m
∗
2
∗
4
10
n*m*2*4^{10}
n∗m∗2∗410
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int n, m, p, k, K;
long long a[1000505], b[1000505], P;//a为前缀积,b为后缀积
int j, i;
int ma[25][25], temp[1048576];
int h[4] = {0, 0, 1, -1}, l[4] = {1, -1, 0, 0};
long long ans;
void dfs(int x, int y, int tot, bool flag, int pick, int cnt)
{
if(cnt == tot)
{
if(flag == false)
++temp[pick];
else
ans += temp[K - 1 - pick];
return;
}
int nx, ny;
for (int z = 0; z < 4; ++z)
{
nx = x + h[z], ny = y + l[z];
if (nx <= 0 || nx > n || ny <= 0 || ny > m)
continue;
if (ma[nx][ny] == ma[i][j] || pick & (1 << ma[nx][ny]))
continue;
dfs(nx, ny, tot, flag, pick | (1 << ma[nx][ny]), cnt + 1);
}
}
int main()
{
long long x, y, z;
int total, cnt = 0;
scanf("%d%d%d%lld%d", &n, &m, &p, &P, &k);
scanf("%lld%lld%lld%lld", &a[0], &x, &y, &z);
if (k == 1)
{
printf("%d\n", n * m);
return 0;
}
x %= P, y %= P, z %= P;
K = 1 << k;
total = n * m + p - 1;
for (i = 1; i <= total; ++i)
a[i] = (a[i - 1] * a[i - 1] % P * x % P + y * a[i - 1] % P + z) % P;
ans = 1;
j = 0;
for (i = p; i <= total; ++i)//把total个数分成K组,每组p个数:[1,p],[p+1,2p],...,[Kp,total]
{
(ans *= a[i]) %= P;//第h+1组的当前前缀积
if (i - p + 1 > j)//第h组的所有后缀积(hp = i)
{
j = i;
ans = 1;
b[i] = a[i];
for (int z = i - 1; z >= i - p + 1; --z)
b[z] = b[z + 1] * a[z] % P;
}
temp[++cnt] = (long long)ans * b[i - p + 1] % P;
}
cnt = 0;
for (i = 1; i <= n; ++i)
for (j = 1; j <= m; ++j)
ma[i][j] = temp[++cnt] % k;
ans = 0;
for (i = 1; i <= n; ++i)
for (j = 1; j <= m; ++j)
{
memset(temp, 0, sizeof(int) * K);
dfs(i, j, k >> 1, false, 1 << ma[i][j], 1);
dfs(i, j, (k >> 1) + k % 2 + 1, true, 0, 1);
}
printf("%lld\n", ans);
return 0;
}