题意:求S1>S2的概率,字符串某些位置可能为空,空的话,里面的字符可以是任意的。
解题思路:先把公式推出来,公式很好推。分三种情况讨论,a[i]==b[i],a[i]==0&&b[i]!=0,a[i]!=0&&b[i]==0 三种情况分别计算概率,然后相加即可!中间所有的除法,用乘法逆元代替!
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int MOD=1e9+7;
ll qpow(ll a,ll b,ll c){
ll ans=1;
ll temp=a;
while(b!=0){
if(b%2)ans=ans*temp%c;
temp=temp*temp%c;
b/=2;
}
return ans;
}
ll a[100005];
ll b[100005];
int main()
{
ll N,M;
cin>>N>>M;
for(int i=0;i<N;i++)
cin>>a[i];
for(int i=0;i<N;i++)
cin>>b[i];
ll one=qpow(M,MOD-2,MOD);
ll two=qpow(M*M%MOD,MOD-2,MOD);
ll ans=0;
ll cur=1;
for(int i=0;i<N;i++){
if(a[i]==0&&b[i]==0){
ans=(ans+cur*((M*M-M)/2)%MOD*two%MOD)%MOD;
cur=cur*one%MOD;
}
else{
if(a[i]==0&&b[i]!=0){
ans=(ans+cur*(M-b[i])%MOD*one%MOD)%MOD;
cur=cur*one%MOD;
}
else{
if(a[i]!=0&&b[i]==0){
ans=(ans+cur*(a[i]-1)%MOD*one%MOD)%MOD;
cur=cur*one%MOD;
}
else{
if(a[i]>b[i]){
ans=(ans+cur)%MOD;
break;
}
else{
if(a[i]==b[i])
continue;
else
break;
}
}
}
}
}
cout<<ans<<endl;
return 0;
}