HTML & JS
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define openfile freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define f(i, x, y) for(int i = x; i < y; i++)
#define all(X) X.begin(), X.end()
#define int long long
#define key pair<int, int>
#define ff first
#define ss second
int mod = 1e9 + 7;
const int inf = 2e18;
using namespace std;

int power(int x, int y)
{
    if(y == 0) return 1;
    int t = power(x, y/2);
    t = (t * t) % mod;
    if(y & 1) t = (t * x) % mod;
    return t;
}

main()
{
    int n, m; cin>>n>>m;
    int a[n+1], b[n+1];
    f(i, 1, n+1) cin>>a[i];
    f(i, 1, n+1) cin>>b[i];
    int t = 1;
    
    int ans = 0;
    int k = 0;
    for(int i = n; i > 0; i--)
    {
        if(a[i] == 0) k++;
        if(b[i] == 0) k++;
    }
    int y = power(m, k);
    f(i, 1, n+1)
    {
        if(a[i] <= b[i] && a[i] != 0 && b[i] != 0) continue;
        else if(a[i] != 0 && b[i] != 0 && a[i] > b[i])
        {
            ans = (ans + (t * power(m, k)) % mod)% mod; break;
        }
        if(a[i] == 0) k--;
        if(b[i] == 0) k--;
    //    cout<<k<<" "<<(a[i] - 1) * power(m, k)<<"\n";
        if(a[i] == 0 && b[i] != 0)
            ans = (ans + ((t * (m - b[i] + mod)%mod) % mod) * power(m, k)) % mod;
        else if(a[i] != 0 && b[i] == 0)
            ans = (ans + (((a[i] - 1 + mod )%mod * t) % mod) * power(m, k)) % mod;
        else
        {
            int x = (m * (m-1) / 2 ) % mod;
            ans = (ans + ((t * x) % mod)*power(m, k))% mod;
            t = (t * m) % mod;
        }
        //cout<<k<<" "<<t<<" ";
    }
    //cout<<ans<<" ";
    cout<<(ans * power(y, mod-2))%mod;
}

Generated URL:

Output:

375000003
Report Bug