題意:一共 個數,連續 個數的乘積 作爲矩陣中一個元素。現在在矩陣中找出一條長度爲 的路徑,且路徑上所有元素在 的意義下均不同。問這樣的路徑有多少條?
思路:首先是求連續 個數的乘積 ,可以把這些數按照 個數爲一組劃分,對於一段連續 個數的乘積即爲其所覆蓋的上一組的後綴積與所覆蓋的這一組的前綴積的乘積。此複雜度爲線性。
其次求長度爲 的路徑,由於 不大於20,可以通過雙向 ,枚舉路徑的中心點,選擇路徑上,通過狀態壓縮來處理,時間複雜度爲
#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;
}