题解:
定义dp状态f[N] [gcd(a[i-2],a[i-1],a[i])] [gcd(a[i-1],a[i])] [a[i]]。但是很多状态是没有用到的,实际上对于m=100时后面三维加起来也不会超过2000,a[i]是gcd(a[i-1],a[i])整数倍,gcd(a[i-1],a[i])是gcd(a[i-2],a[i-1],a[i])的整数倍。
状态转移时枚举新的一维,转移方程为:
f[N+1][ gcd(a[i-1],a[i],a[i+1])) ] [ gcd(a[i],a[i+1]) ] [ a[i+1] ] += f[N] [gcd(a[i-2],a[i-1],a[i])] [gcd(a[i-1],a[i])] [a[i]] * v[ gcd(a[i-2],a[i-1],a[i],a[i+1] ]。
最后答案除以总的概率的逆元。
方程很长,可以预处理状态压缩一下。
#include"bits/stdc++.h"
using namespace std;
typedef long long LL;
int T,n,m;
const int mod = 1e9+7;
const int N = 105;
const int M = 4005;
int a[N],v[N],gcd[N][N],id[N][N][N];
int g[M][N],w[M][N];
LL f[N][M];
LL qpow(LL a, LL n)
{
LL ret = 1;
while(n){
if(n&1) ret = ret*a%mod;
a = a*a%mod;
n >>= 1;
}
return ret;
}
void solve()
{
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
for(int i = 1; i <= m; i++)
scanf("%d",&v[i]);
for(int i = 1; i <= m; i++)
for(int j = 1; j <= m; j++)
gcd[i][j] = __gcd(i,j);
int cnt = 0;
for(int i = 1; i <= m; i++)
for(int j = i; j <= m; j+=i)
for(int k = j; k <= m; k+=j)
id[i][j][k] = ++cnt; //后面三维压缩状态
for(int i = 1; i <= m; i++)
for(int j = i; j <= m; j+=i)
for(int k = j; k <= m; k+=j)
{
int x = id[i][j][k];
for(int y = 1; y <= m; y++)
{
g[x][y] = id[gcd[j][y]][gcd[k][y]][y]; //转移时的下一个状态
w[x][y] = v[gcd[i][y]]; //转移时要乘上的权值
}
}
for(int i = 0; i <= n; i++)
for(int j = 0; j <= cnt; j++)
f[i][j] = 0;
for(int i = 1; i <= m; i++)
for(int j = 1; j <= m; j++)
for(int k = 1; k <= m; k++)
{
if(a[1] && a[1] != i)
continue;
if(a[2] && a[2] != j)
continue;
if(a[3] && a[3] != k)
continue;
f[3][ id[gcd[i][gcd[j][k]]][gcd[j][k]][k] ] += 1;
}
for(int i = 3; i < n; i++)
for(int j = 1; j <= cnt; j++)
for(int k = 1; k <= m; k++)
{
if(a[i+1] && a[i+1] != k) continue;
int nxt = g[j][k];
f[i+1][nxt] = (f[i+1][nxt]+f[i][j]*w[j][k])%mod;
}
LL ans = 0;
for(int j = 1; j <= cnt; j++)
ans = (ans+f[n][j])%mod;
for(int i = 1; i <= n; i++)
if(!a[i])
ans = ans*qpow(m,mod-2)%mod;
cout<<ans<<endl;
}
int main()
{
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif // LOCAL
for(scanf("%d",&T); T; T--)
solve();
return 0;
}