概率的计算答案给出的这张图很清楚了,然后因为要求取模,a/b%M=a*b^-1%M=a*inv(b,M)%M;
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <cstdio> 5 6 using namespace std; 7 const int maxn=100000+10; 8 const int MOD=1000000007; 9 typedef long long LL; 10 int n,m; 11 int s1[maxn],s2[maxn],d[maxn]; 12 void gcd(LL a,LL b,LL &d,LL &x,LL &y){ 13 if(!b){ 14 d=a;x=1;y=0; 15 }else{ 16 gcd(b,a%b,d,y,x); 17 y-=x*(a/b); 18 } 19 } 20 LL inv(LL a,LL n){ 21 LL d,x,y; 22 gcd(a,n,d,x,y); 23 return d==1?(x+n)%n:-1; 24 } 25 LL dp(int a){ 26 if(a==n+1)return 0; 27 if(s1[a]==s2[a]&&s1[a]!=0&&s2[a]!=0)return dp(a+1); 28 if(s1[a]>s2[a]&&s1[a]!=0&&s2[a]!=0)return 1; 29 if(s1[a]<s2[a]&&s1[a]!=0&&s2[a]!=0)return 0; 30 if(s1[a]==0&&s2[a]!=0) 31 return (((m-s2[a])%MOD*inv(m,MOD))%MOD+dp(a+1)%MOD*inv(m,MOD))%MOD; 32 if(s1[a]!=0&&s2[a]==0) 33 return (((s1[a]-1)%MOD*inv(m,MOD))%MOD+(dp(a+1))%MOD*inv(m,MOD))%MOD; 34 if(s1[a]==0&&s2[a]==0) 35 return (((m-1)%MOD*inv(2*m,MOD))%MOD+(dp(a+1)%MOD*inv(m,MOD)))%MOD; 36 } 37 38 39 int main(){ 40 scanf("%d%d",&n,&m); 41 for(int i=1;i<=n;i++)scanf("%d",&s1[i]); 42 for(int i=1;i<=n;i++)scanf("%d",&s2[i]); 43 LL P=dp(1); 44 cout<<P; 45 return 0; 46 }