def f():
    global MOD, ans, factor
    ans %= MOD
    factor %= MOD

MOD = 10**9 + 7

n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

reverse = pow(m, MOD - 2, MOD)
reverse_for_2 = (MOD + 1) // 2
ans = 0
factor = 1
for a, b in zip(a, b):
    if (a == b == 0):
        ans += factor * ((m - 1) * (reverse * reverse_for_2))
        factor *= reverse
        f()
    elif (a == 0):
        ans += factor * (m - b) * reverse
        factor *= reverse
        f()
    elif (b == 0):
        ans += factor * (a - 1) * reverse
        factor *= reverse
        f()
    elif (a > b):
        ans += factor
        f()
        break
    elif (a == b):
        pass
    elif (a < b):
        break
f()
print(ans)


def rev(a, m):
    res = 1
    k = m-2
    s = a
    while k > 0:
        if k%2 == 1:
            res = (res * s) % m
        k //= 2
        s = (s**2) % m
    return res

n, m = [int(x) for x in input().split()]
a1 = [int(x) for x in input().split()]
a2 = [int(x) for x in input().split()]
a = []
mul = 1
for x,y in zip(a1, a2):
    if x == 0 and y == 0:
        count = (m*(m-1))//2
        counteq = m
        maxcount = m**2
    elif x == 0:
        count = m - y
        counteq = 1
        maxcount = m
    elif y == 0:
        count = x-1
        counteq = 1
        maxcount = m
    else:
        count = 1 if x>y else 0
        counteq = 1 if x==y else 0
        maxcount = 1

    a.append((count, counteq, maxcount))
    if counteq == 0: break
a.reverse()

##print(a)

P, Q = 0, 1
for c, ce, mc in a:
    P = (P*ce+ Q*c) % (10**9+7)
    Q = Q*mc

res, zeros = P, Q
print((res * rev(zeros, 10**9+7)) % (10**9+7))


def rev(a, m):
    res = 1
    k = m-2
    s = a
    while k > 0:
        if k%2 == 1:
            res = (res * s) % m
        k //= 2
        s = (s**2) % m
    return res

n, m = [int(x) for x in input().split()]
a1 = [int(x) for x in input().split()]
a2 = [int(x) for x in input().split()]
a = []
mul = 1
for x,y in zip(a1, a2):
    if x == 0 and y == 0:
        count = (m*(m-1))//2
        counteq = m
        maxcount = m**2
    elif x == 0:
        count = m - y
        counteq = 1
        maxcount = m
    elif y == 0:
        count = x-1
        counteq = 1
        maxcount = m
    else:
        count = 1 if x>y else 0
        counteq = 1 if x==y else 0
        maxcount = 1

    a.append((count, counteq, maxcount))
    if counteq == 0: break
a.reverse()

##print(a)

P, Q = 0, 1
for c, ce, mc in a:
    P = P*ce+ Q*c
    Q = Q*mc

res, zeros = P, Q
print((res * rev(zeros, 10**9+7)) % (10**9+7))


def rev(a, m):
    res = 1
    k = m-2
    s = a
    while k > 0:
        if k%2 == 1:
            res = (res * s) % m
        k //= 2
        s = (s**2) % m
    return res

n, m = [int(x) for x in input().split()]
a1 = [int(x) for x in input().split()]
a2 = [int(x) for x in input().split()]
a = []
mul = 1
for x,y in zip(a1, a2):
    if x == 0 and y == 0:
        count = (m*(m-1))//2
        counteq = m
        maxcount = m**2
    elif x == 0:
        count = m - y
        counteq = 1
        maxcount = m
    elif y == 0:
        count = x-1
        counteq = 1
        maxcount = m
    else:
        count = 1 if x>y else 0
        counteq = 1 if x==y else 0
        maxcount = 1

    a.append((count, counteq, maxcount))
    if counteq == 0: break
a.reverse()

##print(a)

P, Q = 0, 1
for c, ce, mc in a:
    P = (P*ce+ Q*c) % (10**9+7)
    Q = (Q*mc)  % (10**9+7)

res, zeros = P, Q
print((res * rev(zeros, 10**9+7)) % (10**9+7))


n, m = list(map(int, input().split(" ")))
s1 = list(map(int, input().split(" ")))
s2 = list(map(int, input().split(" ")))

N = 10 ** 9 + 7
res = True
inv = pow(m, N - 2, N)
cur = 1
result = 0
inv_2 = pow(2, N - 2, N)

for i in range(n):
	if s1[i] == 0 and s2[i] == 0:
		result += (cur * inv_2  * (N + 1 - inv)) % N
		cur *= inv
		continue

	if s1[i] == 0:
		cur *= inv
		result += ((m - s2[i]) * cur) % N
		continue

	if s2[i] == 0:
		cur *= inv
		result += ((s1[i] - 1) * cur) % N
		continue

	if s1[i] < s2[i]:
		break

	if s1[i] > s2[i]:
		result += cur
		break

print(result % N)


n, m = list(map(int, input().split(" ")))
s1 = list(map(int, input().split(" ")))
s2 = list(map(int, input().split(" ")))

N = 10 ** 9 + 7
res = True

def negPow(k):
	return pow(m, N - 1 - k, N)

k = 1
result = 0
for i in range(n):
	if s1[i] == 0 and s2[i] == 0:
		result += (negPow(k-1) * pow(2, N - 2, N) * (N + 1 - negPow(1))) % N
		k += 1
		continue

	if s1[i] == 0:
		result += ((m - s2[i]) * negPow(k)) % N
		k += 1;
		continue

	if s2[i] == 0:
		result += ((s1[i] - 1) * negPow(k)) % N
		k += 1;
		continue

	if s1[i] < s2[i]:
		break

	if s1[i] > s2[i]:
		result += negPow(k - 1)
		break

print(result % N)


n, m = list(map(int, input().split(" ")))
s1 = list(map(int, input().split(" ")))
s2 = list(map(int, input().split(" ")))

N = 10 ** 9 + 7
res = True

def negPow(k):
	return pow(m, N - 1 - k, N)

k = 1
result = 0
for i in range(n):
	if s1[i] == 0 and s2[i] == 0:
		result += (negPow(k) * pow(2, N - 2, N) * (N + 1 - negPow(1))) % N
		k += 1
		continue

	if s1[i] == 0:
		result += ((m - s2[i]) * negPow(k)) % N
		k += 1;
		continue

	if s2[i] == 0:
		result += ((s1[i] - 1) * negPow(k)) % N
		k += 1;
		continue

	if s1[i] < s2[i]:
		break

	if s1[i] > s2[i]:
		result += negPow(k - 1)
		break

print(result % N)


n, m = list(map(int, input().split(" ")))
s1 = list(map(int, input().split(" ")))
s2 = list(map(int, input().split(" ")))

N = 10 ** 9 + 7
res = True
inv = pow(m, N - 2, N)
cur = 1
result = 0

for i in range(n):
	if s1[i] == 0 and s2[i] == 0:
		result += (cur * pow(2, N - 2, N) * (N + 1 - inv)) % N
		cur *= inv
		continue

	if s1[i] == 0:
		cur *= inv
		result += ((m - s2[i]) * cur) % N
		continue

	if s2[i] == 0:
		cur *= inv
		result += ((s1[i] - 1) * cur) % N
		continue

	if s1[i] < s2[i]:
		break

	if s1[i] > s2[i]:
		result += cur
		break

print(result % N)


n, m = list(map(int, input().split(" ")))
s1 = list(map(int, input().split(" ")))
s2 = list(map(int, input().split(" ")))

N = 10 ** 9 + 7
res = True
inv = pow(m, N - 2, N)
cur = 1
result = 0
inv_2 = pow(2, N - 2, N)

for i in range(n):
	if s1[i] == 0 and s2[i] == 0:
		result = (result + cur * inv_2  * (N + 1 - inv)) % N
		cur = (cur * inv) % N
		continue

	if s1[i] == 0:
		cur = (cur * inv) % N
		result = (result + (m - s2[i]) * cur) % N
		continue

	if s2[i] == 0:
		cur = (cur * inv) % N
		result = (result + (s1[i] - 1) * cur) % N
		continue

	if s1[i] < s2[i]:
		break

	if s1[i] > s2[i]:
		result = (result + cur) % N
		break

print(result % N)


rd = lambda: map(int, input().split())
M = 1000000007
inv = lambda x: (M - M // x) * inv(M % x) % M if x - 1 else 1
n, m = rd()
a = list(rd())
b = list(rd())
i = 0
p, q, r = 0, 1, 1
while i < n:
    x, y = a[i], b[i]
    if x == 0 and y == 0:
        p = (p * m * m + r * ((m - 1) * m >> 1)) % M
        q = q * m * m % M
        r = r * m % M
    elif x == 0:
        p = (p * m + r * (m - y)) % M
        q = q * m % M
    elif y == 0:
        p = (p * m + r * (x - 1)) % M
        q = q * m % M
    else:
        if x == y:
            pass
        else:
            if x > y:
                p = (p + r) % M
            break
    i += 1
print(p * inv(q) % M)


rd = lambda: map(int, input().split())
M = 1000000007
inv = lambda x: (M - M // x) * inv(M % x) % M if x - 1 else 1
n, m = rd()
a = list(rd())
b = list(rd())
p, q, r = 0, 1, 1
for i in range(n):
    x, y = a[i], b[i]
    if x == 0 and y == 0:
        p = (p * m * m + r * ((m - 1) * m >> 1)) % M
        q = q * m * m % M
        r = r * m % M
    elif x == 0:
        p = (p * m + r * (m - y)) % M
        q = q * m % M
    elif y == 0:
        p = (p * m + r * (x - 1)) % M
        q = q * m % M
    elif x != y:
        if x > y:
            p = (p + r) % M
        break
print(p * inv(q) % M)


rd = lambda: map(int, input().split())
M = 1000000007
inv = lambda x: (M - M // x) * inv(M % x) % M if x - 1 else 1
n, m = rd()
a = list(rd())
b = list(rd())
i = 0
p, q, r = 0, 1, 1
while i < n:
    x, y = a[i], b[i]
    if x == 0 and y == 0:
        p = (p * m + r * (m + 1) * m >> 1) % M
        q = q * m * m % M
        r = r * m % M
    elif x == 0:
        p = (p * m + r * (m - y)) % M
        q = q * m % M
    elif y == 0:
        p = (p * m + r * (x - 1)) % M
        q = q * m % M
    else:
        if x == y:
            pass
        else:
            if x > y:
                p = (p + r) % M
            break
    i += 1
print(p * inv(q) % M)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 3:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

def fraction(x,y):
    return x * modInv(y) % MOD

ans = 0
for a, b in zip(l1, l2):
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * fraction(m - b, m) % MOD
        elif a > 0:
            ans += probLeft * fraction(a - 1, m) % MOD
        else:
            ans += probLeft * fraction((m - 1) * m // 2, m * m) % MOD
        ans %= MOD
        probLeft = probLeft * fraction(1, m) % MOD
    elif a > b:
        ans += probLeft
        ans %= MOD
        break
    elif a == b:
        continue
    else:
        break

print(ans)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 1:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

ans = 0
for i in range(n):
    a = l1[i]
    b = l2[i]
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * fraction(m - b, m) % MOD
        elif a > 0:
            ans += probLeft * fraction(a - 1, m) % MOD
        else:
            ans += probLeft * fraction((m - 1) * m // 2, m * m) % MOD
        probLeft = probLeft * fraction(1, m) % MOD
    elif a > b:
        ans += probLeft
        break
    elif a == b:
        continue
    else:
        break

print(ans % MOD)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 1:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

minv = fraction(1, m)

ans = 0
for i in range(n):
    a = l1[i]
    b = l2[i]
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * (m - b) * minv % MOD
        elif a > 0:
            ans += probLeft * (a - 1) * minv % MOD
        else:
            ans += probLeft * ((m - 1) * m // 2) * minv * minv % MOD
        probLeft = probLeft * minv % MOD
    elif a > b:
        ans += probLeft
        break
    elif a == b:
        continue
    else:
        break

print(ans % MOD)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 1:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

minv = fraction(1, m)

ans = 0
for i in range(n):
    a = l1[i]
    b = l2[i]
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * (m - b) * minv % MOD
        elif a > 0:
            ans += probLeft * (a - 1) * minv % MOD
        else:
            ans += probLeft * ((m - 1) * m // 2) * minv * minv % MOD
        probLeft = probLeft * minv % MOD
    elif a > b:
        ans += probLeft
        break
    else:
        break

print(ans % MOD)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 1:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

minv = fraction(1, m)

ans = 0
for i in range(n):
    a = l1[i]
    b = l2[i]
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * (m - b) * minv % MOD
        elif a > 0:
            ans += probLeft * fraction(a - 1, m) % MOD
        else:
            ans += probLeft * fraction((m - 1) * m // 2, m * m) % MOD
        probLeft = probLeft * fraction(1, m) % MOD
    elif a > b:
        ans += probLeft
        break
    else:
        break

print(ans % MOD)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 1:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

ans = 0
for a, b in zip(l1, l2):
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * fraction(m - b, m) % MOD
        elif a > 0:
            ans += probLeft * fraction(a - 1, m) % MOD
        else:
            ans += probLeft * fraction((m - 1) * m // 2, m * m) % MOD
        probLeft = probLeft * fraction(1, m) % MOD
    elif a > b:
        ans += probLeft
        break
    elif a == b:
        continue
    else:
        break

print(ans % MOD)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 3:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

ans = 0
for a, b in zip(l1, l2):
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * fraction(m - b, m) % MOD
        elif a > 0:
            ans += probLeft * fraction(a - 1, m) % MOD
        else:
            ans += probLeft * fraction((m - 1) * m // 2, m * m) % MOD
        ans %= MOD
        probLeft = probLeft * fraction(1, m) % MOD
    elif a > b:
        ans += probLeft
        ans %= MOD
        break
    elif a == b:
        continue
    else:
        break

print(ans)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 3:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

ans = 0
for a, b in zip(l1, l2):
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * fraction(m - b, m) % MOD
        elif a > 0:
            ans += probLeft * fraction(a - 1, m) % MOD
        else:
            ans += probLeft * fraction((m - 1) * m // 2, m * m) % MOD
        probLeft = probLeft * fraction(1, m) % MOD
    elif a > b:
        ans += probLeft
        break
    elif a == b:
        continue
    else:
        break

print(ans % MOD)


MOD = 1000000007

n, m = map(int, input().split())
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]

probLeft = 1 # probability that I'm continuing

def modInv(x, n = MOD - 2):
    if n <= 1:
        return (x ** n) % MOD
    tmp = (modInv(x, n // 2) ** 2) % MOD
    if n % 2 == 1:
        tmp = tmp * x % MOD
    return tmp

dp = {}

def fraction(x,y):
    if (x,y) in dp:
        return dp[(x,y)]
    dp[(x,y)] = x * modInv(y) % MOD
    return dp[(x,y)]

minv = fraction(1, m)
oo = ((m - 1) * m // 2) * minv * minv % MOD

ans = 0
for i in range(n):
    a = l1[i]
    b = l2[i]
    if a == 0 or b == 0:
        if b > 0:
            ans += probLeft * (m - b) * minv % MOD
        elif a > 0:
            ans += probLeft * (a - 1) * minv % MOD
        else:
            ans += probLeft * oo % MOD
        probLeft = probLeft * minv % MOD
    elif a > b:
        ans += probLeft
        break
    else:
        break

print(ans % MOD)


MOD = 10**9 + 7
n,m = [int(x) for x in input().split()]
s1 = [int(x) for x in input().split()]
s2 = [int(x) for x in input().split()]

mi = pow(m, MOD - 2, MOD)
m2 = pow(2, MOD - 2, MOD)
ans = 0
mul = 1
for a,b in zip(s1, s2):
	if a == 0 and b == 0:
		ans = (ans + mul * ((m - 1)*(mi * m2))) % MOD
		mul = (mul * mi) % MOD
	elif a == 0:
		ans = (ans + (mul * (m - b) * mi)) % MOD
		mul = (mul * mi) % MOD
	elif b == 0:
		ans = (ans + mul * (a - 1) * mi) % MOD
		mul = (mul * mi) % MOD
	elif a > b:
		ans = (ans + mul * 1) %  MOD
		break
	elif a == b:
		pass
	elif a < b:
		break
print(ans % MOD)


from fractions import Fraction
MOD = 10**9 + 7
n,m = [int(x) for x in input().split()]
s1 = [int(x) for x in input().split()]
s2 = [int(x) for x in input().split()]

ans = Fraction(0, 1)
mul = Fraction(1, 1)
for a,b in zip(s1, s2):
	if a == 0 and b == 0:
		ans = ans + mul * Fraction(m - 1, 2*m)
		mul = mul * Fraction(1, m)
	elif a == 0:
		ans = ans + mul * Fraction(m - b, m)
		mul = mul * Fraction(1, m)
	elif b == 0:
		ans = ans + mul * Fraction(a - 1, m)
		mul = mul * Fraction(1, m)
	elif a > b:
		ans = ans + mul * 1
		break
	elif a == b:
		pass
	elif a < b:
		break
u = ans.numerator
d = ans.denominator
print((u * pow(d, MOD - 2, MOD)) % MOD)


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, n):
        r = RN(self.u * n.d + n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, n):
        r = RN(self.u * n.u, self.d * n.d)
        r.cleanup()
        return r

    def one_minus(self):
        return RN(self.d - self.u, self.d)

    def get_m_exp(self):
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n+1) * n)//2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                return groreq.get_m_exp()
        else:
            if gr == sm == 0:
                pass
                strgr = strgr.add(strgr.one_minus().mult(RN(sum_ch(m-1) , m*m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(sum_ch(m) , m*m)))

            elif gr == 0:
                strgr = strgr.add(strgr.one_minus().mult(RN(m - sm, m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(m - sm + 1, m)))

            else:
                strgr = strgr.add( strgr.one_minus().mult(RN(gr-1, m)))
                groreq = groreq.add( groreq.one_minus().mult(RN(gr, m)))

    return strgr.get_m_exp()

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def __str__(self):
       return str(self.u) +  '/' +  str(self.d)

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, n):
        r = RN(self.u * n.d + n.u * self.d, self.d * n.d)
        #r.cleanup()
        return r

    def minus(self, n):
        r = RN(self.u * n.d - n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, n):
        r = RN(self.u * n.u, self.d * n.d)
        #r.cleanup()
        return r

    def one_minus(self):
        return RN(self.d - self.u, self.d)

    def get_m_exp(self):
        self.cleanup()
        #print(str(self))
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n+1) * n)//2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)

    eq = RN(1, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                return strgr.add(eq).get_m_exp()
        else:
            if gr == sm == 0:
                strgr = strgr.add(eq.mult(RN(sum_ch(m-1) , m*m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(sum_ch(m) , m*m)))

            elif gr == 0:
                strgr = strgr.add(eq.mult(RN(m - sm, m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(m - sm + 1, m)))

            else:
                strgr = strgr.add( eq.mult(RN(gr-1, m)))
                groreq = groreq.add( groreq.one_minus().mult(RN(gr, m)))
            eq = eq.mult(RN(1,m))
    return strgr.get_m_exp()

'''a = sol([0,0],[1,1], 2) # 3/4

a = sol([0,0,0],[1,1,1], 2) # 7/8
a = sol([0,1,1],[1,1,1], 2) # 1/2
a = sol([1,0,1],[1,1,1], 2) # 1/2

a = sol([0,0,0],[1,3,3], 3) # 2/2
a = sol([0,0,0],[1,1,0], 2) # 5/8
a = sol([0,0,0],[0,0,0], 2) #
'''

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def __str__(self):
        return str(self.u) + '/' + str(self.d)

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, u, d):
        self.u = self.u * d + u * self.d
        self.d = self.d * d

    def minus(self, n):
        r = RN(self.u * n.d - n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, u, d):
        # r.cleanup()
        return self.u * u, self.d * d

    def mult_ip(self, u, d):
        # r.cleanup()
        self.u, self.d = self.u * u, self.d * d

    def one_minus_mult(self, u, d):
        self.u, self.d = self.u * u, self.d * d
        return self.d - self.u, self.d

    def get_m_exp(self):
        self.cleanup()
        # print(str(self))
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n + 1) * n) // 2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)

    eq = RN(1, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                strgr.add(eq.u, eq.d)
                return strgr.get_m_exp()
        else:
            if gr == sm == 0:
                strgr.add(*eq.mult(sum_ch(m - 1), m * m))
                groreq.add(*groreq.one_minus_mult(sum_ch(m), m * m))

            elif gr == 0:
                strgr.add(*eq.mult(m - sm, m))
                groreq.add(*groreq.one_minus_mult(m - sm + 1, m))

            else:
                strgr.add(*eq.mult(gr - 1, m))
                groreq.add(*groreq.one_minus_mult(gr, m))
            eq.mult_ip(1, m)
    return strgr.get_m_exp()

'''
a = sol([0,0],[1,1], 2) # 3/4

a = sol([0,0,0],[1,1,1], 2) # 7/8
a = sol([0,1,1],[1,1,1], 2) # 1/2
a = sol([1,0,1],[1,1,1], 2) # 1/2

a = sol([0,0,0],[1,3,3], 3) # 2/2
a = sol([0,0,0],[1,1,0], 2) # 5/8
a = sol([0,0,0],[0,0,0], 2) # 13/16
'''

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def __str__(self):
        return str(self.u) + '/' + str(self.d)

    def cleanup(self):
        self.u = self.u % p
        self.d = self.d % p

    def add(self, u, d):
        self.u = self.u * d + u * self.d
        self.d = self.d * d
        self.cleanup()

    def mult(self, u, d):

        return (self.u * u)%p, (self.d * d)%p

    def mult_ip(self, u, d):
        # r.cleanup()
        self.u, self.d = self.u * u, (self.d * d) % p

    def get_m_exp(self):
        self.cleanup()
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

        # print(str(self))
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n + 1) * n) // 2

def sol(s1, s2, m):
    strgr = RN(0, 1)

    eq = RN(1, 1)
    for gr, sm, i in zip(s1, s2, range(len(s1))):

        strgr.cleanup()

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                strgr.add(eq.u, eq.d)
                return strgr.get_m_exp()
        else:
            if gr == sm == 0:
                strgr.add(*eq.mult(sum_ch(m - 1), m * m))

            elif gr == 0:
                strgr.add(*eq.mult(m - sm, m))

            else:
                strgr.add(*eq.mult(gr - 1, m))
            eq.mult_ip(1, m)
    return strgr.get_m_exp()

'''
a = sol([0,0],[1,1], 2) # 3/4

a = sol([0,0,0],[1,1,1], 2) # 7/8
a = sol([0,1,1],[1,1,1], 2) # 1/2
a = sol([1,0,1],[1,1,1], 2) # 1/2

a = sol([0,0,0],[1,3,3], 3) # 2/2
a = sol([0,0,0],[1,1,0], 2) # 5/8
a = sol([0,0,0],[0,0,0], 2) # 13/16
'''

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, n):
        r = RN(self.u * n.d + n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, n):
        r = RN(self.u * n.u, self.d * n.d)
        r.cleanup()
        return r

    def one_minus(self):
        return RN(self.d - self.u, self.d)

    def get_m_exp(self):
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n+1) * n)//2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                return groreq.get_m_exp() if groreq.u != 0 else RN(1,1).get_m_exp()
        else:
            if gr == sm == 0:
                pass
                strgr = strgr.add(strgr.one_minus().mult(RN(sum_ch(m-1) , m*m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(sum_ch(m) , m*m)))

            elif gr == 0:
                strgr = strgr.add(strgr.one_minus().mult(RN(m - sm, m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(m - sm + 1, m)))

            else:
                strgr = strgr.add( strgr.one_minus().mult(RN(gr-1, m)))
                groreq = groreq.add( groreq.one_minus().mult(RN(gr, m)))

    return strgr.get_m_exp()

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def __str__(self):
       return str(self.u) +  '/' +  str(self.d)

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, n):
        r = RN(self.u * n.d + n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def minus(self, n):
        r = RN(self.u * n.d - n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, n):
        r = RN(self.u * n.u, self.d * n.d)
        r.cleanup()
        return r

    def one_minus(self):
        return RN(self.d - self.u, self.d)

    def get_m_exp(self):
        #print(str(self))
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n+1) * n)//2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)

    eq = RN(1, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                return strgr.add(eq).get_m_exp()
        else:
            if gr == sm == 0:
                strgr = strgr.add(eq.mult(RN(sum_ch(m-1) , m*m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(sum_ch(m) , m*m)))

            elif gr == 0:
                strgr = strgr.add(eq.mult(RN(m - sm, m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(m - sm + 1, m)))

            else:
                strgr = strgr.add( eq.mult(RN(gr-1, m)))
                groreq = groreq.add( groreq.one_minus().mult(RN(gr, m)))
            eq = eq.mult(RN(1,m))
    return strgr.get_m_exp()

'''a = sol([0,0],[1,1], 2) # 3/4

a = sol([0,0,0],[1,1,1], 2) # 7/8
a = sol([0,1,1],[1,1,1], 2) # 1/2
a = sol([1,0,1],[1,1,1], 2) # 1/2

a = sol([0,0,0],[1,3,3], 3) # 2/2
a = sol([0,0,0],[1,1,0], 2) # 5/8
a = sol([0,0,0],[0,0,0], 2) #
'''

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def __str__(self):
       return str(self.u) +  '/' +  str(self.d)

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, u, d):
        self.u = self.u * d + u * self.d
        self.d = self.d * d

    def minus(self, n):
        r = RN(self.u * n.d - n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, u, d):
        #r.cleanup()
        return self.u * u, self.d * d
    def mult_ip(self, u, d):
        #r.cleanup()
        self.u, self.d =  self.u * u, self.d * d

    def one_minus_mult(self, u, d):
        self.u, self.d = self.u * u, self.d * d
        return self.d - self.u, self.d

    def get_m_exp(self):
        self.cleanup()
        #print(str(self))
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n+1) * n)//2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)

    eq = RN(1, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                strgr.add(eq)
                return strgr.get_m_exp()
        else:
            if gr == sm == 0:
                strgr.add(*eq.mult(sum_ch(m-1) , m*m))
                groreq.add(*groreq.one_minus_mult(sum_ch(m) , m*m))

            elif gr == 0:
                strgr.add(*eq.mult(m - sm, m))
                groreq.add(*groreq.one_minus_mult(m - sm + 1, m))

            else:
                strgr.add(* eq.mult(gr-1, m))
                groreq.add( *groreq.one_minus_mult(gr, m))
            eq.mult_ip(1,m)
    return strgr.get_m_exp()
'''
a = sol([0,0],[1,1], 2) # 3/4

a = sol([0,0,0],[1,1,1], 2) # 7/8
a = sol([0,1,1],[1,1,1], 2) # 1/2
a = sol([1,0,1],[1,1,1], 2) # 1/2

a = sol([0,0,0],[1,3,3], 3) # 2/2
a = sol([0,0,0],[1,1,0], 2) # 5/8
a = sol([0,0,0],[0,0,0], 2) # 13/16
'''

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def __str__(self):
       return str(self.u) +  '/' +  str(self.d)

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, n):
        r = RN(self.u * n.d + n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def minus(self, n):
        r = RN(self.u * n.d - n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, n):
        r = RN(self.u * n.u, self.d * n.d)
        r.cleanup()
        return r

    def one_minus(self):
        return RN(self.d - self.u, self.d)

    def get_m_exp(self):
        print(str(self))
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n+1) * n)//2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)

    eq = RN(1, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                return strgr.add(eq).get_m_exp()
        else:
            if gr == sm == 0:
                strgr = strgr.add(eq.mult(RN(sum_ch(m-1) , m*m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(sum_ch(m) , m*m)))

            elif gr == 0:
                strgr = strgr.add(eq.mult(RN(m - sm, m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(m - sm + 1, m)))

            else:
                strgr = strgr.add( eq.mult(RN(gr-1, m)))
                groreq = groreq.add( groreq.one_minus().mult(RN(gr, m)))
            eq = eq.mult(RN(1,m))
    return strgr.get_m_exp()

'''a = sol([0,0],[1,1], 2) # 3/4

a = sol([0,0,0],[1,1,1], 2) # 7/8
a = sol([0,1,1],[1,1,1], 2) # 1/2
a = sol([1,0,1],[1,1,1], 2) # 1/2

a = sol([0,0,0],[1,3,3], 3) # 2/2
a = sol([0,0,0],[1,1,0], 2) # 5/8
a = sol([0,0,0],[0,0,0], 2) #
'''

print(sol(s1, s2, m))


from math import gcd

p = 10 ** 9 + 7

class RN:
    p = 10 ** 9 + 7

    def __init__(self, u, d):
        self.u = u
        self.d = d

    def __str__(self):
       return str(self.u) +  '/' +  str(self.d)

    def cleanup(self):
        a = gcd(self.u, self.d)
        self.u //= a
        self.d //= a

    def add(self, n):
        r = RN(self.u * n.d + n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def minus(self, n):
        r = RN(self.u * n.d - n.u * self.d, self.d * n.d)
        r.cleanup()
        return r

    def mult(self, n):
        r = RN(self.u * n.u, self.d * n.d)
        r.cleanup()
        return r

    def one_minus(self):
        return RN(self.d - self.u, self.d)

    def get_m_exp(self):
        #print(str(self))
        return ((pow(self.d, p - 2, p)) * self.u) % p

n, m = tuple(map(int, input().split()))
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))

def sum_ch(n):
    return ((n+1) * n)//2

def sol(s1, s2, m):
    strgr = RN(0, 1)
    groreq = RN(0, 1)

    eq = RN(1, 1)
    for gr, sm in zip(s1, s2):

        if gr != 0 and sm != 0:

            if gr == sm:
                continue
            elif gr < sm:
                return strgr.get_m_exp()
            else:
                return strgr.add(eq).get_m_exp()
        else:
            if gr == sm == 0:
                pass
                strgr = strgr.add(groreq.one_minus().mult(eq).mult(RN(sum_ch(m-1) , m*m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(sum_ch(m) , m*m)))

            elif gr == 0:
                strgr = strgr.add(strgr.one_minus().mult(eq).mult(RN(m - sm, m)))
                groreq = groreq.add(groreq.one_minus().mult(RN(m - sm + 1, m)))

            else:
                strgr = strgr.add( strgr.one_minus().mult(eq).mult(RN(gr-1, m)))
                groreq = groreq.add( groreq.one_minus().mult(RN(gr, m)))
            eq = eq.mult(RN(1,m))
    return strgr.get_m_exp()

print(sol(s1, s2, m))


n, m = map(int, input().split())
s1 = map(int, input().split())
s2 = map(int, input().split())

MOD = 10 ** 9 + 7
invm = pow(m, MOD - 2, MOD)
inv2 = pow(2, MOD - 2, MOD)

z = 0
p = 1

for a, b in zip(s1, s2):
    if a == 0 and b == 0:
        z = (z + p * ((m - 1) * (invm * inv2))) % MOD
        p = (p * invm) % MOD
    elif a == 0:
        z = (z + (p * (m - b) * invm)) % MOD
        p = (p * invm) % MOD
    elif b == 0:
        z = (z + (p * (a - 1) * invm)) % MOD
        p = (p * invm) % MOD
    elif a > b:
        z = (z + p) % MOD
        break
    elif a < b:
        break
print(z)


import sys, math

#f = open('input/input_2', 'r')
f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else:
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) ** 2
    if (y & 1 == 1):
      p *= x
    return (p % m)

# Function to return gcd of a and b
def gcd(a, b) :
    while (a != 0):
      t = b % a
      b = a
      a = t
    return b

n, m = map(int, f.readline().split())
s1 = map(int, f.readline().split())
s2 = map(int, f.readline().split())
#0 same, 1 big
pos = [1, 0]
all_pos = [1, 1]

for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) // 2
    next_pos[1] += pos[1] * m * m

    all_pos[0] *= m*m
    all_pos[1] *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos[0] *= m
    all_pos[1] *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos[0] *= m
    all_pos[1] *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]

  pos = next_pos
  if pos[0] == 0:
    break
  for j in range(2):
    g = gcd(pos[j], all_pos[j])
    pos[j] //= g
    all_pos[j] //= g

p = pos[1]
q = all_pos[1]
pq_gcd = gcd(p,q)
p //= pq_gcd
q //= pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


import sys, math

#f = open('input/input_2', 'r')
f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else :
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) % m
    p = (p * p) % m
    if(y % 2 == 0) :
        return p
    else :
        return ((x * p) % m)

# Function to return gcd of a and b
def gcd(a, b) :
    if (a == 0) :
        return b
    return gcd(b % a, a)

n, m = map(int, f.readline().split())
s1 = map(int, f.readline().split())
s2 = map(int, f.readline().split())
#0 same, 1 big
pos = [1, 0]
all_pos = 1
for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) // 2
    next_pos[1] += pos[1] * m * m

    all_pos *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]
  pos = next_pos
  if pos[0] == 0:
    break

p = pos[1]
q = all_pos
pq_gcd = gcd(p,q)
p //= pq_gcd
q //= pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


import sys, math

f = open('input/input_2', 'r')
#f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else :
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) % m
    p = (p * p) % m
    if(y % 2 == 0) :
        return p
    else :
        return ((x * p) % m)

# Function to return gcd of a and b
def gcd(a, b) :
    if (a == 0) :
        return b
    return gcd(b % a, a)

n, m = map(int, f.readline().split())
s1 = list(map(int, f.readline().split()))
s2 = list(map(int, f.readline().split()))
#0 same, 1 big
pos = [1, 0]
all_pos = 1
for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) / 2
    next_pos[1] += pos[1] * m * m

    all_pos *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]
  pos = next_pos

p = pos[1]
q = all_pos
pq_gcd = gcd(p,q)
p//=pq_gcd
q//=pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


import sys, math

#f = open('input/input_2', 'r')
f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else :
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) % m
    p = (p * p) % m
    if(y % 2 == 0) :
        return p
    else :
        return ((x * p) % m)

# Function to return gcd of a and b
def gcd(a, b) :
    if (a == 0) :
        return b
    return gcd(b % a, a)

n, m = map(int, f.readline().split())
s1 = list(map(int, f.readline().split()))
s2 = list(map(int, f.readline().split()))
#0 same, 1 big
pos = [1, 0]
all_pos = 1
for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) / 2
    next_pos[1] += pos[1] * m * m

    all_pos *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]
  pos = next_pos

p = pos[1]
q = all_pos
pq_gcd = gcd(p,q)
p//=pq_gcd
q//=pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


import sys, math

f = open('input/input_2', 'r')
#f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else:
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) ** 2
    if (y & 1 == 1):
      p *= x
    return (p % m)

# Function to return gcd of a and b
def gcd(a, b) :
    while (a != 0):
      t = b % a
      b = a
      a = t
    return b

n, m = map(int, f.readline().split())
s1 = map(int, f.readline().split())
s2 = map(int, f.readline().split())
#0 same, 1 big
pos = [1, 0]
all_pos = [1, 1]

for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) // 2
    next_pos[1] += pos[1] * m * m

    all_pos[0] *= m*m
    all_pos[1] *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos[0] *= m
    all_pos[1] *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos[0] *= m
    all_pos[1] *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]

  pos = next_pos
  if pos[0] == 0:
    break
  for j in range(2):
    g = gcd(pos[j], all_pos[j])
    pos[j] //= g
    all_pos[j] //= g

p = pos[1]
q = all_pos[1]
pq_gcd = gcd(p,q)
p //= pq_gcd
q //= pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


import sys, math

#f = open('input/input_2', 'r')
f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else:
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) ** 2
    if (y & 1 == 1):
      p *= x
    return (p % m)

# Function to return gcd of a and b
def gcd(a, b) :
    while (a != 0):
      t = b % a
      b = a
      a = t
    return b

n, m = map(int, f.readline().split())
s1 = map(int, f.readline().split())
s2 = map(int, f.readline().split())

#0 same, 1 big
pos = [1, 0]
all_pos = 1
for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) // 2
    next_pos[1] += pos[1] * m * m

    all_pos *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]
  pos = next_pos
  if pos[0] == 0:
    break
  g = gcd(pos[0], all_pos)
  g = gcd(pos[1], g)
  pos[0] //= g
  pos[1] //= g
  all_pos //= g
  pos[0] %= 1000000007
  pos[1] %= 1000000007
  all_pos %= 1000000007

p = pos[1]
q = all_pos
pq_gcd = gcd(p,q)
p //= pq_gcd
q //= pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


import sys, math

#f = open('input/input_2', 'r')
f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else:
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) ** 2
    if (y & 1 == 1):
      p *= x
    return (p % m)

# Function to return gcd of a and b
def gcd(a, b) :
    while (a != 0):
      t = b % a
      b = a
      a = t
    return b

n, m = map(int, f.readline().split())
s1 = map(int, f.readline().split())
s2 = map(int, f.readline().split())
#0 same, 1 big
pos = [1, 0]
all_pos = 1
for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) // 2
    next_pos[1] += pos[1] * m * m

    all_pos *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]
  pos = next_pos
  if pos[0] == 0:
    break

  g = gcd(pos[0], all_pos)
  g = gcd(pos[1], g)
  pos[0] //= g
  pos[1] //= g
  all_pos //= g

p = pos[1]
q = all_pos
pq_gcd = gcd(p,q)
p //= pq_gcd
q //= pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


import sys, math

#f = open('input/input_2', 'r')
f = sys.stdin

def modInverse(a, m) :
    g = gcd(a, m)
    if (g != 1) :
        return None
    else :
        return  power(a, m - 2, m)

# To compute x^y under modulo m
def power(x, y, m) :
    if (y == 0) :
        return 1
    p = power(x, y // 2, m) % m
    p = (p * p) % m
    if(y % 2 == 0) :
        return p
    else :
        return ((x * p) % m)

# Function to return gcd of a and b
def gcd(a, b) :
    if (a == 0) :
        return b
    return gcd(b % a, a)

n, m = map(int, f.readline().split())
s1 = list(map(int, f.readline().split()))
s2 = list(map(int, f.readline().split()))
#0 same, 1 big
pos = [1, 0]
all_pos = 1
for a1, a2 in zip(s1, s2):
  next_pos = [0, 0]
  if a1 == 0 and a2 == 0:
    next_pos[0] += pos[0] * m
    next_pos[1] += pos[0] * m * (m-1) // 2
    next_pos[1] += pos[1] * m * m

    all_pos *= m*m
  elif a1 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (m - a2)
    next_pos[1] += pos[1] * m

    all_pos *= m
  elif a2 == 0:
    next_pos[0] += pos[0]
    next_pos[1] += pos[0] * (a1 - 1)
    next_pos[1] += pos[1] * m

    all_pos *= m
  else:
    if a1 > a2:
      next_pos[1] += pos[0]
    elif a1 == a2:
      next_pos[0] += pos[0]
    next_pos[1] += pos[1]
  pos = next_pos

p = pos[1]
q = all_pos
pq_gcd = gcd(p,q)
p //= pq_gcd
q //= pq_gcd

q_inv = modInverse(q, 1000000007)
print( (p * q_inv) % 1000000007)


n, m = [int(x) for x in input().split()]
s1 = [int(x) for x in input().split()]
s2 = [int(x) for x in input().split()]
mod = int(1e9 + 7)

e = 1
res = 1
mi = pow(m, mod - 2, mod)
mi2 = pow(2 * m, mod - 2, mod)
mis = pow(m**2, mod - 2, mod)
to = 1
ss = 0
# for i in range(0, n):
#     if (s1[i] != 0 and s2[i] == 0) or (s1[i] == 0 and s2[i] != 0):
#         to = (to * m) % mod
#     elif s1[i] == 0 and s2[i] == 0:
#         to = (to * m * m) % mod

for i in range(n):
    if s1[i] == 0 and s2[i] != 0:
#         to = (to * mi) % mod
        res = (((((res * (m - s2[i]) % mod) * mi) % mod) * e) * to)% mod
    elif s1[i] != 0 and s2[i] == 0:
#         to = (to * mi) % mod
        res = (((((res * (s1[i] - 1) % mod) * mi) % mod) * e) * to)% mod
    elif s1[i] == 0 and s2[i] == 0:
#         to = (to * mis) % mod
        res = (((((res * (m - 1) % mod) * mi2) % mod) * e) * to)% mod

    else:
        if s1[i] > s2[i]:
            ss = ((e * to) % mod + ss) % mod
            break
        if s1[i] < s2[i]:
            break
    e = (e * mi) % mod
    ss = (res + ss) % mod
    print(res)
print(ss % mod)


n, m = [int(x) for x in input().split()]
s1 = [int(x) for x in input().split()]
s2 = [int(x) for x in input().split()]
mod = int(1e9 + 7)

e = 1
res = 1
mi = pow(m, mod - 2, mod)
mi2 = pow(2 * m, mod - 2, mod)
mis = pow(m**2, mod - 2, mod)
to = 1
ss = 0
# for i in range(0, n):
#     if (s1[i] != 0 and s2[i] == 0) or (s1[i] == 0 and s2[i] != 0):
#         to = (to * m) % mod
#     elif s1[i] == 0 and s2[i] == 0:
#         to = (to * m * m) % mod

for i in range(n):
    if s1[i] == 0 and s2[i] != 0:
#         to = (to * mi) % mod
        res = (((((res * (m - s2[i]) % mod) * mi) % mod) * e) * to)% mod
    elif s1[i] != 0 and s2[i] == 0:
#         to = (to * mi) % mod
        res = (((((res * (s1[i] - 1) % mod) * mi) % mod) * e) * to)% mod
    elif s1[i] == 0 and s2[i] == 0:
#         to = (to * mis) % mod
        res = (((((res * (m - 1) % mod) * mi2) % mod) * e) * to)% mod

    else:
        if s1[i] > s2[i]:
            ss = ((e * to) % mod + ss) % mod
            break
        if s1[i] < s2[i]:
            break
    e = (e * mi) % mod
    ss = (res + ss) % mod
print(ss % mod)


n, m = [int(x) for x in input().split()]
s1 = [int(x) for x in input().split()]
s2 = [int(x) for x in input().split()]
mod = int(1e9 + 7)

e = 1
mi = pow(m, mod - 2, mod)
mi2 = pow(2 * m, mod - 2, mod)
res = 0

for i in range(n):
    if s1[i] == 0 and s2[i] != 0:
        res += ((((m - s2[i]) * mi) % mod) * e) %mod
        e = (e * mi) % mod
    elif s1[i] != 0 and s2[i] == 0:
        res += ((((s1[i] - 1) * mi) % mod) * e) %mod
        e = (e * mi) % mod
    elif s1[i] == 0 and s2[i] == 0:
        res += ((((m - 1)* mi2) % mod) * e)%mod
        e = (e * mi) % mod
    else:
        if s1[i] > s2[i]:
            res += e
            break
        if s1[i] < s2[i]:
            break
    res = res % mod
print(res%mod)


n, m = [int(x) for x in input().split()]
s1 = [int(x) for x in input().split()]
s2 = [int(x) for x in input().split()]
mod = int(1e9 + 7)

e = 1
mi = pow(m, mod - 2, mod)
mi2 = pow(2 * m, mod - 2, mod)
res = 0

for i in range(n):
    if s1[i] == 0 and s2[i] != 0:
        res += ((((m - s2[i]) * mi) % mod) * e) %mod
    elif s1[i] != 0 and s2[i] == 0:
        res += ((((s1[i] - 1) * mi) % mod) * e) %mod
    elif s1[i] == 0 and s2[i] == 0:
        res += ((((m - 1)* mi2) % mod) * e)%mod

    else:
        if s1[i] > s2[i]:
            res += e
            break
        if s1[i] < s2[i]:
            break
    e = (e * mi) % mod
    res = res % mod
print(res%mod)


n, m = [int(x) for x in input().split()]

a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]

mult = 1
mod = 10 ** 9 + 7
res = 0

m_inv = pow(m, mod - 2, mod)

for x, y in zip(a, b):
    if x and y:
        if x > y:
            res += mult
            res %= mod
            break
        elif x == y:
            continue
        else:
            break
    elif x:
        res += mult * (x-1) * m_inv % mod
        res %= mod
        mult = mult * m_inv % mod
    elif y:
        res += mult * (m - y) * m_inv % mod
        res %= mod
        mult = mult * m_inv % mod
    else:
        res += mult * m * (m - 1) // 2 * m_inv * m_inv % mod
        res %= mod
        mult = mult * m_inv % mod
print(res)


n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
MOD = int(1e9 + 7)
m2 = pow(2, MOD - 2, MOD)
mm = pow(m, MOD - 2, MOD)
f = 1
ans = 0
for i, j in zip(a, b):
    if i == 0 and j == 0:
        ans += (m - 1) * m2 * mm * f
        ans %= MOD
        f = f * mm % MOD
    elif i == 0:
        ans += (m - j) * f * mm
        ans %= MOD
        f = f * mm % MOD
    elif j == 0:
        ans += (i - 1) * f * mm
        ans %= MOD
        f = f * mm % MOD
    elif i > j:
        ans += f
        ans %= MOD
        break
    elif i < j:
        break

print(ans)


import sys

MOD = 1000000007

def solve(io):
  N = io.readInt()
  M = io.readInt()
  S = io.readIntArray(N)
  T = io.readIntArray(N)

  P = 0
  Q = 1
  A = 1
  B = 1
  for i in range(0, N):
    if S[i] == 0 or T[i] == 0:
      if S[i] == 0 and T[i] == 0:
        gtTop = M * (M - 1) * A
        gtBot = 2 * M * M * B
        eqTop = 1
        eqBot = M
      elif S[i] == 0:
        gtTop = (M - T[i]) * A
        gtBot = M * B
        eqTop = 1
        eqBot = M
      elif T[i] == 0:
        gtTop = (S[i] - 1) * A
        gtBot = M * B
        eqTop = 1
        eqBot = M
    elif S[i] > T[i]:
      gtTop = A
      gtBot = B
      eqTop = 0
      eqBot = 1
    elif S[i] > T[i]:
      gtTop = 0
      gtBot = 0
      eqTop = 0
      eqBot = 1
    elif S[i] == T[i]:
      gtTop = 0
      gtBot = 1
      eqTop = 1
      eqBot = 1
    P, Q = P * gtBot + gtTop * Q, Q * gtBot
    P %= MOD
    Q %= MOD
    A = (A * eqTop) % MOD
    B = (B * eqBot) % MOD
    if S[i] != 0 and T[i] != 0 and S[i] < T[i]:
      break
  io.println((P * modinv(Q, MOD)) % MOD)

def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

def modinv(a, m):
	g, x, _ = extended_gcd(a, m)
	if g != 1:
		raise ValueError
	return x % m

# +---------------------+
# | TEMPLATE CODE BELOW |
# |    DO NOT MODIFY    |
# +---------------------+

# TODO: maybe reading byte-by-byte is faster than reading and parsing tokens.
class IO:
  input = None
  output = None
  raw = ""
  buf = []
  pos = 0

  def __init__(self, inputStream, outputStream):
    self.input = inputStream
    self.output = outputStream

  def readToBuffer(self):
    self.raw = self.input.readline().rstrip('\n')
    self.buf = self.raw.split()
    self.pos = 0

  def readString(self):
    while self.pos == len(self.buf):
      self.readToBuffer()
    ans = self.buf[self.pos]
    self.pos += 1
    return ans

  def readInt(self):
    return int(self.readString())

  def readFloat(self):
    return float(self.readString())

  def readStringArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readString())
    return arr

  def readIntArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readInt())
    return arr

  def readFloatArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readFloat())
    return arr

  def readLine(self):
    while self.pos == len(self.buf):
      self.readToBuffer()
    if self.pos > 0:
      raise ValueError("Cannot call readline in the middle of a line.")
    return self.raw

  def print(self, s):
    self.output.write(str(s))

  def println(self, s):
    self.print(s)
    self.print('\n')

  def flushOutput(self):
    self.output.flush()

pythonIO = IO(sys.stdin, sys.stdout)
solve(pythonIO)
pythonIO.flushOutput()


import sys

MOD = 1000000007

def solve(io):
  N = io.readInt()
  M = io.readInt()
  S = io.readIntArray(N)
  T = io.readIntArray(N)

  P = 0
  Q = 1
  A = 1
  B = 1
  for i in range(0, N):
    if S[i] == 0 or T[i] == 0:
      if S[i] == 0 and T[i] == 0:
        gtTop = M * (M - 1) * A
        gtBot = 2 * M * M * B
        eqTop = 1
        eqBot = M
      elif S[i] == 0:
        gtTop = (M - T[i]) * A
        gtBot = M * B
        eqTop = 1
        eqBot = M
      elif T[i] == 0:
        gtTop = (S[i] - 1) * A
        gtBot = M * B
        eqTop = 1
        eqBot = M
    elif S[i] > T[i]:
      gtTop = A
      gtBot = B
      eqTop = 0
      eqBot = 1
    elif S[i] < T[i]:
      gtTop = 0
      gtBot = 1
      eqTop = 0
      eqBot = 1
    elif S[i] == T[i]:
      gtTop = 0
      gtBot = 1
      eqTop = 1
      eqBot = 1
    P, Q = P * gtBot + gtTop * Q, Q * gtBot
    P %= MOD
    Q %= MOD
    A = (A * eqTop) % MOD
    B = (B * eqBot) % MOD
    if S[i] != 0 and T[i] != 0 and S[i] != T[i]:
      break
  io.println((P * modinv(Q, MOD)) % MOD)

def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

def modinv(a, m):
	g, x, _ = extended_gcd(a, m)
	if g != 1:
		raise ValueError
	return x % m

# +---------------------+
# | TEMPLATE CODE BELOW |
# |    DO NOT MODIFY    |
# +---------------------+

# TODO: maybe reading byte-by-byte is faster than reading and parsing tokens.
class IO:
  input = None
  output = None
  raw = ""
  buf = []
  pos = 0

  def __init__(self, inputStream, outputStream):
    self.input = inputStream
    self.output = outputStream

  def readToBuffer(self):
    self.raw = self.input.readline().rstrip('\n')
    self.buf = self.raw.split()
    self.pos = 0

  def readString(self):
    while self.pos == len(self.buf):
      self.readToBuffer()
    ans = self.buf[self.pos]
    self.pos += 1
    return ans

  def readInt(self):
    return int(self.readString())

  def readFloat(self):
    return float(self.readString())

  def readStringArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readString())
    return arr

  def readIntArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readInt())
    return arr

  def readFloatArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readFloat())
    return arr

  def readLine(self):
    while self.pos == len(self.buf):
      self.readToBuffer()
    if self.pos > 0:
      raise ValueError("Cannot call readline in the middle of a line.")
    return self.raw

  def print(self, s):
    self.output.write(str(s))

  def println(self, s):
    self.print(s)
    self.print('\n')

  def flushOutput(self):
    self.output.flush()

pythonIO = IO(sys.stdin, sys.stdout)
solve(pythonIO)
pythonIO.flushOutput()


from fractions import gcd;

def add(a,b,c,d):
	lcm =(b*d)//(gcd(b,d));
	aa = lcm//b;
	bb = lcm//d;
	#print("aa:",aa,"bb:",bb,"a:",a,"b:",b);
	aa = aa*a;
	bb = bb*c;
	#print("aa:",aa,"bb:",bb);
	cc = aa+bb;
	dd = gcd(lcm,cc);
	#print("cc:",cc);
	#print("lcm:",lcm);
	lcm = lcm//dd;
	cc = cc //dd;
	#print("cc:",cc);
	#print("lcm:",lcm);
	return cc,lcm;

def mul(a,b,c,d):
	aa = a*c;
	bb = b*d;
	dd = gcd(aa,bb);
	aa = aa//dd;
	bb = bb//dd;

	return aa,bb;

def eeuclid(a,b):
	q = a//b;
	r = a % b;

	if r == 1:
		return 1,-q;

	a,b = eeuclid(b,r);
	m = 1;
	n = -q;
	m = m * b;
	n = n * b;
	n = n + a;

	return m,n;

n,m = input().split();
n = int(n);
m = int(m);

arr1 = [];
arr2 = [];

arr1 = [int(x) for x in input().split()];
arr2 = [int(x) for x in input().split()];

num = [];
den = [];

for i in range(0,n):
	num.append(0);
	den.append(0);
num.append(0);
den.append(1);

for i in range(n-1,-1,-1):
	if(arr1[i] != 0 and arr2[i] != 0):
		if(arr1[i] > arr2[i]):
			num[i] = 1;
			den[i] = 1;
		elif(arr1[i] == arr2[i]):
			if(num[i+1] == 0 and den[i+1] == 1):
				num[i] = 0;
				den[i] = 1;
			else:
				num[i] = num[i+1];
				den[i] = den[i+1];

		elif(arr1[i] < arr2[i]):
			num[i] = 0;
			den[i] = 1;
	elif(arr1[i] == 0 and arr2[i] != 0):
		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = m-arr2[i];
			den[i] = m;
		else:
			left = m-arr2[i];
			a,b = mul(1,m,num[i+1],den[i+1]);
			c,d = add(a,b,left,m);
			num[i] = c;
			den[i] = d;
	elif(arr1[i] != 0 and arr2[i] == 0):
		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = arr1[i]-1;
			den[i] = m;
		else:
			a,b = mul(1,m,num[i+1],den[i+1]);
			#print("a:",a);
			#print("b:",b);
			c,d = add(arr1[i]-1,m,a,b);
			num[i] = c;
			den[i] = d;
	else:
		aa = (m * (m-1))/2;
		bb = (m-1)*m*m;

		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = aa;
			den[i] = bb;
		else:
			cc,dd = mul(1,m,num[i+1],den[i+1]);
			cc,dd = add(aa,bb,cc,dd);
			num[i] = cc;
			den[i] = dd;

	#print(num[i],den[i]);

#print(num[0],den[0]);
aaa,bbb = eeuclid(den[0],1000000007);
aaa = aaa % 1000000007;

aaa = aaa * num[0];
aaa = aaa % 1000000007;

print(aaa);


from fractions import gcd;

def add(a,b,c,d):
	lcm =(b*d)//(gcd(b,d));
	aa = lcm//b;
	bb = lcm//d;
	#print("aa:",aa,"bb:",bb,"a:",a,"b:",b);
	aa = aa*a;
	bb = bb*c;
	#print("aa:",aa,"bb:",bb);
	cc = aa+bb;
	dd = gcd(lcm,cc);
	#print("cc:",cc);
	#print("lcm:",lcm);
	lcm = lcm//dd;
	cc = cc //dd;
	#print("cc:",cc);
	#print("lcm:",lcm);
	return cc,lcm;

def mul(a,b,c,d):
	aa = a*c;
	bb = b*d;
	dd = gcd(aa,bb);
	aa = aa//dd;
	bb = bb//dd;

	return aa,bb;

def eeuclid(a,b):
	q = a//b;
	r = a % b;

	if r == 1:
		return 1,-q;

	a,b = eeuclid(b,r);
	m = 1;
	n = -q;
	m = m * b;
	n = n * b;
	n = n + a;

	return m,n;

n,m = input().split();
n = int(n);
m = int(m);

arr1 = [];
arr2 = [];

arr1 = [int(x) for x in input().split()];
arr2 = [int(x) for x in input().split()];

num = [];
den = [];

for i in range(0,n):
	num.append(0);
	den.append(0);
num.append(0);
den.append(1);

for i in range(n-1,-1,-1):
	if(arr1[i] != 0 and arr2[i] != 0):
		if(arr1[i] > arr2[i]):
			num[i] = 1;
			den[i] = 1;
		elif(arr1[i] == arr2[i]):
			if(num[i+1] == 0 and den[i+1] == 1):
				num[i] = 0;
				den[i] = 1;
			else:
				num[i] = num[i+1];
				den[i] = den[i+1];

		elif(arr1[i] < arr2[i]):
			num[i] = 0;
			den[i] = 1;
	elif(arr1[i] == 0 and arr2[i] != 0):
		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = m-arr2[i];
			den[i] = m;
		else:
			left = m-arr2[i];
			a,b = mul(1,m,num[i+1],den[i+1]);
			c,d = add(a,b,left,m);
			num[i] = c;
			den[i] = d;
	elif(arr1[i] != 0 and arr2[i] == 0):
		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = arr1[i]-1;
			den[i] = m;
		else:
			a,b = mul(1,m,num[i+1],den[i+1]);
			#print("a:",a);
			#print("b:",b);
			c,d = add(arr1[i]-1,m,a,b);
			num[i] = c;
			den[i] = d;
	else:
		aa = (m * (m-1))//2;
		bb = m*m;

		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = aa;
			den[i] = bb;
		else:
			cc,dd = mul(1,m,num[i+1],den[i+1]);
			cc,dd = add(aa,bb,cc,dd);
			num[i] = cc;
			den[i] = dd;

	#print(num[i],den[i]);

#print(num[0],den[0]);
aaa,bbb = eeuclid(den[0],1000000007);
aaa = aaa % 1000000007;

aaa = aaa * num[0];
aaa = aaa % 1000000007;

print(aaa);


from fractions import gcd;

def add(a,b,c,d):
	lcm =(b*d)//(gcd(b,d));
	aa = lcm//b;
	bb = lcm//d;
	#print("aa:",aa,"bb:",bb,"a:",a,"b:",b);
	aa = aa*a;
	bb = bb*c;
	#print("aa:",aa,"bb:",bb);
	cc = aa+bb;
	dd = gcd(lcm,cc);
	#print("cc:",cc);
	#print("lcm:",lcm);
	lcm = lcm//dd;
	cc = cc //dd;
	#print("cc:",cc);
	#print("lcm:",lcm);
	return cc,lcm;

def mul(a,b,c,d):
	aa = a*c;
	bb = b*d;
	dd = gcd(aa,bb);
	aa = aa//dd;
	bb = bb//dd;

	return aa,bb;

def eeuclid(a,b):
	q = a//b;
	r = a % b;

	if r == 1:
		return 1,-q;

	a,b = eeuclid(b,r);
	m = 1;
	n = -q;
	m = m * b;
	n = n * b;
	n = n + a;

	return m,n;

def mod_inverse(val,m):
	a,b = eeuclid(val,m);
	return a % m;

n,m = input().split();
n = int(n);
m = int(m);
mod_val = 1000000007;
arr1 = [];
arr2 = [];

arr1 = [int(x) for x in input().split()];
arr2 = [int(x) for x in input().split()];

num = [];
den = [];
prob = [];

for i in range(0,n):
	num.append(0);
	den.append(0);
	prob.append(0);
num.append(0);
den.append(1);
prob.append(0);

for i in range(n-1,-1,-1):
	if(arr1[i] != 0 and arr2[i] != 0):
		if(arr1[i] > arr2[i]):
			prob[i] = 1;
		elif(arr1[i] == arr2[i]):
			if(prob[i+1] == 0):
				prob[i] = 0;
			else:
				prob[i] = prob[i+1];
		elif(arr1[i] < arr2[i]):
			prob[i] = 0;

	elif(arr1[i] == 0 and arr2[i] != 0):
		num1 = m-arr2[i];
		inv1 = mod_inverse(m,mod_val);
		inv1 = inv1 % mod_val;
		qq = ((num1 % mod_val) * (inv1 % mod_val)) % mod_val;

		pp = inv1 * prob[i+1];

		prob[i] = (qq + pp) % mod_val;

	elif(arr1[i] != 0 and arr2[i] == 0):
		num1 = arr1[i]-1;
		inv1 = mod_inverse(m,mod_val);

		qq = ((num1 % mod_val) * (inv1 % mod_val)) % mod_val;

		pp = inv1 * prob[i+1];
		prob[i] = (qq + pp) % mod_val;
	else:
		aa = (m * (m-1))//2;
		aa = aa % mod_val;

		inv2 = mod_inverse(m*m,mod_val);
		inv1 = mod_inverse(m,mod_val);

		qq = (aa * inv2) % mod_val;
		pp = (inv1 * prob[i+1]) % mod_val;

		prob[i] = (pp + qq) % mod_val;

print(prob[0]);


from fractions import gcd;

def add(a,b,c,d):
	lcm =(b*d)//(gcd(b,d));
	aa = lcm//b;
	bb = lcm//d;

	aa = aa*a;
	bb = bb*c;
	cc = aa+bb;
	dd = gcd(lcm,cc);
	lcm = lcm//dd;
	cc = cc //dd;

	return cc,lcm;

def mul(a,b,c,d):
	aa = a*c;
	bb = b*d;
	dd = gcd(aa,bb);
	aa = aa//dd;
	bb = bb//dd;

	return aa,bb;

def eeuclid(a,b):
	q = a//b;
	r = a % b;

	if r == 1:
		return 1,-q;

	a,b = eeuclid(b,r);
	m = 1;
	n = -q;
	m = m * b;
	n = n * b;
	n = n + a;

	return m,n;

n,m = input().split();
n = int(n);
m = int(m);

arr1 = [];
arr2 = [];

arr1 = [int(x) for x in input().split()];
arr2 = [int(x) for x in input().split()];

num = [];
den = [];

for i in range(0,n):
	num.append(0);
	den.append(0);
num.append(0);
den.append(1);

for i in range(n-1,-1,-1):
	if(arr1[i] != 0 and arr2[i] != 0):
		if(arr1[i] > arr2[i]):
			num[i] = 1;
			den[i] = 1;
		elif(arr1[i] == arr2[i]):
			if(num[i+1] == 0 and den[i+1] == 1):
				num[i] = 0;
				den[i] = 1;
			else:
				num[i] = num[i+1];
				den[i] = den[i+1];

		elif(arr1[i] < arr2[i]):
			num[i] = 0;
			den[i] = 1;
	elif(arr1[i] == 0 and arr2[i] != 0):
		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = m-arr2[i];
			den[i] = m;
		else:
			left = m-arr2[i];
			a,b = mul(1,m,num[i+1],den[i+1]);
			c,d = add(a,b,left,m);
			num[i] = c;
			den[i] = d;
	elif(arr1[i] != 0 and arr2[i] == 0):
		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = arr1[i]-1;
			den[i] = m;
		else:
			a,b = mul(1,m,num[i+1],den[i+1]);
			c,d = add(arr2[i]-1,m,a,b);
			num[i] = c;
			den[i] = d;
	else:
		aa = (m * (m-1))/2;
		bb = (m-1)*m*m;

		if(num[i+1] == 0 and den[i+1] == 1):
			num[i] = aa;
			den[i] = bb;
		else:
			cc,dd = mul(1,m,num[i+1],den[i+1]);
			cc,dd = add(aa,bb,cc,dd);
			num[i] = cc;
			den[i] = dd;

aaa,bbb = eeuclid(den[0],1000000007);
aaa = aaa % 1000000007;

aaa = aaa * num[0];
aaa = aaa % 1000000007;

print(aaa);


mod = 1000000007
def pow(a,b,c):
    n = 1
    m = a
    v = b
    if a == 1:
        return 1
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m %= c
        v //= 2
    return n%c

n,m = map(int, input().split())

a = list(map(int, input().split()))
b = list(map(int, input().split()))
z = [0 for i in range(n+10)]

for i in range(n)[::-1]:
    z[i] = z[i+1]
    if a[i] == 0:
        z[i] += 1
    if b[i] == 0:
        z[i] += 1
ans = 0
cmb = 1

if z[0] == 0:
    if a > b:
        print(1)
    else:
        print(0)
    quit()
inverse_two = pow(2,mod-2,mod)
com = (m*(m-1))%mod*inverse_two%mod
for i in range(n):
    if a[i] != 0 and b[i] != 0:
        if a[i] > b[i]:
            ans += cmb*pow(m,z[i+1],mod)%mod
        break
    elif a[i] == 0 and b[i] == 0:
        ans += cmb*com*pow(m,z[i+1],mod)%mod
        cmb *= m
    elif a[i] == 0:
        ans += (cmb*(m-b[i]))%mod*pow(m,z[i+1],mod)%mod
    elif b[i] == 0:
        ans += (cmb*(a[i]-1))%mod*pow(m,z[i+1],mod)%mod
    ans %= mod

k = pow(m,z[0],mod)
k = pow(k,mod-2,mod)
ans *= k
ans %= mod
print(ans)


mod = 1000000007
def pow(a,b,c):
    n = 1
    m = a
    v = b
    if a == 1:
        return 1
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m %= c
        v //= 2
    return n%c

n,m = map(int, input().split())

a = list(map(int, input().split()))
b = list(map(int, input().split()))
z = [0 for i in range(n+10)]

for i in range(n)[::-1]:
    z[i] = z[i+1]
    if a[i] == 0:
        z[i] += 1
    if b[i] == 0:
        z[i] += 1
ans = 0
cmb = 1
inverse_two = pow(2,mod-2,mod)
com = (m*(m-1))%mod*inverse_two%mod
for i in range(n):
    if a[i] != 0 and b[i] != 0:
        if a[i] > b[i]:
            ans += cmb*pow(m,z[i+1],mod)%mod
        break
    elif a[i] == 0 and b[i] == 0:
        ans += cmb*com*pow(m,z[i+1],mod)%mod
        cmb *= m
    elif a[i] == 0:
        ans += (cmb*(m-b[i]))%mod*pow(m,z[i+1],mod)%mod
    elif b[i] == 0:
        ans += (cmb*(a[i]-1))%mod*pow(m,z[i+1],mod)%mod
    ans %= mod

k = pow(m,z[0],mod)
k = pow(k,mod-2,mod)
ans *= k
ans %= mod
print(ans)


mod = 1000000007
def pow(a,b,c):
    n = 1
    m = a
    v = b
    if a == 1:
        return 1
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m %= c
        v //= 2
    return n%c

n,m = map(int, input().split())

a = list(map(int, input().split()))
b = list(map(int, input().split()))
z = [0 for i in range(n+10)]

for i in range(n)[::-1]:
    z[i] = z[i+1]
    if a[i] == 0:
        z[i] += 1
    if b[i] == 0:
        z[i] += 1
ans = 0
cmb = 1

if z[0] == 0:
    if a > b:
        print(1)
    else:
        print(0)
    quit()
inverse_two = pow(2,mod-2,mod)
com = (m*(m-1))%mod*inverse_two%mod
for i in range(n):
    if a[i] != 0 and b[i] != 0:
        if a[i] > b[i]:
            ans += cmb*pow(m,z[i+1],mod)%mod
        break
    elif a[i] == 0 and b[i] == 0:
        ans += (cmb*com)%mod*pow(m,z[i+1],mod)%mod
        cmb *= m
        cmb %= mod
    elif a[i] == 0:
        ans += (cmb*(m-b[i]))%mod*pow(m,z[i+1],mod)%mod
    elif b[i] == 0:
        ans += (cmb*(a[i]-1))%mod*pow(m,z[i+1],mod)%mod
    ans %= mod

k = pow(m,z[0],mod)
k = pow(k,mod-2,mod)
ans *= k
ans %= mod
print(ans)


#!usr/bin/env python3
#! = map(int, input().split())
#! = [int(input()) for i in range()]

#A
mod = 1000000007
def pow(a,b,c):
    n = 1
    m = a
    v = b
    if a == 1:
        return 1
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m %= c
        v //= 2
    return n%c

n,m = map(int, input().split())

a = list(map(int, input().split()))
b = list(map(int, input().split()))
z = [0 for i in range(n+10)]

for i in range(n)[::-1]:
    z[i] = z[i+1]
    if a[i] == 0:
        z[i] += 1
    if b[i] == 0:
        z[i] += 1
ans = 0
cmb = 1
inverse_two = pow(2,mod-2,mod)
com = (m*(m-1))%mod*inverse_two%mod
for i in range(n):
    if a[i] != 0 and b[i] != 0:
        if a[i] > b[i]:
            ans += cmb*pow(m,z[i+1],mod)%mod
            break
    elif a[i] == 0 and b[i] == 0:
        ans += cmb*com*pow(m,z[i+1],mod)%mod
        cmb *= m
    elif a[i] == 0:
        ans += (cmb*(m-b[i]))%mod*pow(m,z[i+1],mod)%mod
    elif b[i] == 0:
        ans += (cmb*(a[i]-1))%mod*pow(m,z[i+1],mod)%mod
    ans %= mod
k = pow(m,z[0],mod)
k = pow(k,mod-2,mod)
ans *= k
ans %= mod
print(ans)

#B
"""
def gcd(a,b):
    if a == 0:
        return b
    return gcd(b%a, a)

def pow(a,b,c):
    n = 1
    m = a
    v = b
    if a == 1:
        return 1
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m%= c
        v //= 2
    return n%c

mod = 1000000007
T = int(input())
for _ in range(T):
    l,d,t = map(int, input().split())
    cos_p = d
    q = l
    g = abs(gcd(cos_p, q))
    cos_p *= pow(g,mod-2,mod)
    cos_p %= mod
    q *= pow(g,mod-2,mod)
    q %= mod
    sin_p = (q**2 - cos_p**2)**(1/2)
    lis_p = []
    lis_q = []
    flag = False
    if q % 2 == 0:
        flag = True
    while t > 0:
        if t % 2 == 1:
            lis_p.append([cos_p, sin_p])
            lis_q.append(q)
        sin_p = 2*sin_p*cos_p
        cos_p = 2*cos_p**2-q**2
        q = q**2
        if flag:
            g = abs(gcd(cos_p, q))
            cos_p *= pow(g,mod-2,mod)
            cos_p %= mod
            sin_p /= g
            q *= pow(g,mod-2,mod)
            q %= mod
        else:
            cos_p %= mod
            q %= mod
        t //= 2

    while len(lis_p) > 1:
        cos_p1, sin_p1 = lis_p.pop(0)
        cos_p2, sin_p2 = lis_p.pop(0)
        q1 = lis_q.pop(0)
        q2 = lis_q.pop(0)
        cos = cos_p1*cos_p2-sin_p1*sin_p2
        cos = round(cos)
        sin = sin_p1*cos_p2+cos_p1*sin_p2
        q = q1*q2
        if flag:
            g = abs(gcd(cos,q))
            cos *= pow(g,mod-2,mod)
            cos %= mod
            sin /= g
            q *= pow(g,mod-2,mod)
            q %= mod
        else:
            cos_p %= mod
            sin_p %= mod
        lis_p.append([cos, sin])
        lis_q.append(q)

    p = lis_p[0][0]
    q = lis_q[0]
    print(p,q)
    p *= l
    g = abs(gcd(p,q))
    p *= pow(l,mod-2,mod)
    p %= mod
    q *= pow(l,mod-2,mod)
    q %= mod
    print(p*q%mod)
"""
"""
def pow(a,b,c):
    n = 1
    m = a
    v = b
    if a == 1:
        return 1
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m%= c
        v //= 2
    return n%c

mod = 1000000007
print(-23*pow(27,mod-2,mod)*3%mod)
T = int(input())
for _ in range(T):
    l,d,t = map(int, input().split())
    cos = d*pow(l, mod-2, mod)
    sin2 = (1-cos**2%mod)%mod
    lis = []
    k = t
    while k > 0:
        if k % 2 == 1:
            lis.append([cos, sin2])
        sin2 = 4*sin2*cos**2
        sin2 %= mod
        cos = 2*cos**2-1
        cos %= mod
        k //= 2
    while len(lis) > 1:
        cos_1, sin_12 = lis.pop(0)
        cos_2, sin_22 = lis.pop(0)
        sin_2 = round(sin_12*sin_22)
        while 1:
            sin = sin_2**(1/2)
            if abs(sin-round(sin)) <= 0.00001:
                break
            sin_2 -= mod
        sin = round(sin)%mod
        cos = cos_1*cos_2%mod-sin
        sin2 = sin_12*cos_2**2%mod+cos_1**2*sin_22%mod+(2*sin*(cos_1*cos_2)%mod)%mod
        sin2 %= mod
        cos %= mod
        lis.append([cos, sin2])
    cos = lis[0][0]
    ans = l*cos%mod
    print(ans)
"""
#C
"""
import math
def pow(a,b,c):
    n = 1
    m = a
    v = b
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m%= c
        v //= 2
    return n%c

def su(a,b,c):
    if b == 1:
        return 1
    if b % 2 == 0:
        return (1+pow(a, b//2, c))*su(a,b//2,c)
    else:
        return (1+a*su(a,b-1,c))
n = int(input())
s = [list(map(int, input().split())) for i in range(n)]
s = s[::-1]
b = int(input())
ans = 0
k = 0
if b == 1:
    print(0)
    quit()
for i,j in s:
    d = math.floor(math.log(i,10))+1
    q = su(10**d, j,b)
    a = i*q*pow(10, k,b)%b
    a %= b
    ans += a
    ans %= b
    k += j*d
print(int(ans))
"""

#D
"""
def is_prime(n):
    i = 2
    if n == 1:
        return True
    while i**2 <= n:
        if n%i == 0:
            return False
        i += 1
    return True

p,y = map(int, input().split())
for i in range(1, y+1)[::-1]:
    if is_prime(i):
        break

for z in range(max(i, p+1), y+1)[::-1]:
    flag = True
    for j in range(2,p+1):
        if z % j == 0:
            flag = False
            break
        if j**2 >= z+1:
            break
    if flag:
        print(z)
        quit()
print(-1)
"""

#E
"""
m,n = map(int, input().split())
a = list(map(int, input().split()))
if n == 1:
    d = 0
    x = a[0]
"""
#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T


mod = 1000000007
def pow(a,b,c):
    n = 1
    m = a
    v = b
    if a == 1:
        return 1
    while v > 0:
        if v%2 == 1:
            n *= m%c
            n %= c
        m *= m
        m %= c
        v //= 2
    return n%c

n,m = map(int, input().split())

a = list(map(int, input().split()))
b = list(map(int, input().split()))
z = [0 for i in range(n+10)]

for i in range(n)[::-1]:
    z[i] = z[i+1]
    if a[i] == 0:
        z[i] += 1
    if b[i] == 0:
        z[i] += 1
ans = 0
cmb = 1

if z[0] == 0:
    if a > b:
        print(1)
    else:
        print(0)
    quit()
for i in range(len(z)):
    z[i] = pow(m,z[i],mod)
inverse_two = pow(2,mod-2,mod)
com = (m*(m-1))%mod*inverse_two%mod
for i in range(n):
    if a[i] != 0 and b[i] != 0:
        if a[i] > b[i]:
            ans += cmb*z[i+1]%mod
        break
    elif a[i] == 0 and b[i] == 0:
        ans += (cmb*com)%mod*z[i+1]%mod
        cmb *= m
    elif a[i] == 0:
        ans += (cmb*(m-b[i]))%mod*z[i+1]%mod
    elif b[i] == 0:
        ans += (cmb*(a[i]-1))%mod*z[i+1]%mod
    ans %= mod

ans *= pow(z[0],mod-2,mod)
ans %= mod
print(ans)


mod=10**9+7
n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
ans=0
mul=1
for i in range(n):
	if a[i]==0 and b[i]==0:
		x=((m-1)*pow(m*2,mod-2,mod))
		x%=mod
		ans+=(x*mul)
		ans%=mod
		mul*=pow(m,mod-2,mod)
		mul%=mod
	elif a[i]==0:
		x=((m-b[i])*pow(m,mod-2,mod))
		x%=mod
		ans+=(x*mul)
		ans%=mod
		mul*=pow(m,mod-2,mod)
		mul%=mod
	elif b[i]==0:
		x=((a[i]-1)*pow(m,mod-2,mod))
		x%=mod
		ans+=(x*mul)
		ans%=mod
		mul*=pow(m,mod-2,mod)
		mul%=mod
	elif a[i]==b[i]:
		continue;
	elif a[i]>b[i]:
		ans+=mul
		ans%=mod
		break
	else:
		break
print ans


mod=10**9+7
n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
f=1
ind=n
lind=n
for i in range(n):
	if a[i]==0 or b[i]==0:
		continue
	if a[i]>b[i]:
		ind=i
		f=0
		break
	if b[i]>a[i]:
		ind=i
		f=1
		break
for i in range(ind):
	if a[i]==0 and b[i]==0:
		lind=i
		break
ans=0
mul=1
for i in range(ind):
	if a[i]==0 and b[i]==0:
		if i==lind-1 and f:
			x=((m-1)*pow(m*m,mod-2,mod))
		else:
			x=(m*pow(m*m,mod-2,mod))
		x%=mod
		ans+=(x*mul)
		ans%=mod
		mul*=pow(m*m,mod-2,mod)
		mul%=mod
	elif a[i]==0:
		if i==lind-1 and f:
			x=((m-b[i])*pow(m,mod-2,mod))
		else:
			x=((m-b[i]+1)*pow(m,mod-2,mod))
		x%=mod
		ans+=(x*mul)
		ans%=mod
		mul*=pow(m,mod-2,mod)
		mul%=mod
	elif b[i]==0:
		if i==lind-1 and f:
			x=((a[i]-1)*pow(m,mod-2,mod))
		else:
			x=(a[i]*pow(m,mod-2,mod))
		x%=mod
		ans+=(x*mul)
		ans%=mod
		mul*=pow(m,mod-2,mod)
		mul%=mod
print ans


n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
num=1
den=1
rem=10**9+7
first=0
for i in range(n):
    x=a[i]
    y=b[i]
ans=0
eq=1
for i in range(n):
    x=a[i]
    y=b[i]
    #print x,y
    if x==0 and y==0:
        p=(m-1)*eq
        p%=rem
        p=(p%rem)*pow(2*m,rem-2,rem)
        ans=(ans+p)%rem
        eq=eq*pow(m,rem-2,rem)
        eq%=rem
    elif x==0 and y!=0:
        p=(m-y)*eq
        p%=rem
        p=((p%rem)*pow(m,rem-2,rem))%rem
        #print p
        ans = (ans + p) % rem
        eq = eq * pow(m, rem - 2, rem)
        eq%=rem
    elif x!=0 and y==0:
        p=(x-1)*eq
        p%=rem
        p = (p % rem) * pow(m, rem - 2, rem)
        ans = (ans + p) % rem
        eq = eq * pow(m, rem - 2, rem)
        eq%=rem
    else:
        if x==y:
            continue
        elif x>y:
            #print eq
            ans=(ans+eq)%rem
            break
        else:
            break
print ans%rem


def gcd(a, b):
    if not b:
        return a
    else:
        return gcd(b, a % b)
n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
num=1
den=1
rem=10**9+7
first=0
for i in range(n):
    x=a[i]
    y=b[i]
ans=0
eq=1
for i in range(n):
    x=a[i]
    y=b[i]
    #print x,y
    if x==0 and y==0:
        p=(m-1)*eq
        p=(p%rem)*pow(2*m,rem-2,rem)
        ans=(ans+p)%rem
        eq=eq*pow(m,rem-2,rem)
    elif x==0 and y!=0:
        p=(m-y)*eq

        p=((p%rem)*pow(m,rem-2,rem))%rem
        #print p
        ans = (ans + p) % rem
        eq = eq * pow(m, rem - 2, rem)
    elif x!=0 and y==0:
        p=(x-1)*eq
        p = (p % rem) * pow(m, rem - 2, rem)
        ans = (ans + p) % rem
        eq = eq * pow(m, rem - 2, rem)
    else:
        if x==y:
            continue
        elif x>y:
            #print eq
            ans=(ans+eq)
            break
        else:
            break
print ans%rem


raw_input()
s=raw_input()
a=p=0
x=[0,0]
for c in s:
 a+=x[0]==x[1]and c==p;x[c<'U']+=1;p=c
print(a)


p=10**9+7
n,m=raw_input().split()
n=int(n)
m=int(m)
a=raw_input().split()
b=raw_input().split()
a=[int(k) for k in a]
b=[int(k) for k in b]
invm=pow(m,p-2,p)
inv2=pow(2,p-2,p)
ans=0
for i in reversed(range(n)):
	if a[i]==0 and b[i]==0:
		ans=(((inv2*invm)%p)*(m-1)+invm*ans)%p
	if a[i]==0 and b[i]!=0:
		ans= ((m-b[i])*invm+invm*ans)%p
	if a[i]!=0 and b[i]==0:
		ans= ((a[i]-1)*invm+invm*ans)%p
	if a[i]!=0 and b[i]!=0:
		if a[i]>b[i]:
			ans= 1
		elif b[i]>a[i]:
			ans= 0
		else:
			ans= ans
print(ans)


x=raw_input().split(' ')
n=int(x[0])
m=int(x[1])
y=raw_input().split(' ')
mod=1000000007
arr=[]
i=0
while i<n:
    arr.append(int(y[i]))
    i=i+1

y=raw_input().split(' ')
brr=[]
i=0
while i<n:
    brr.append(int(y[i]))
    i=i+1

i=0
p=1
sm=0
while i<n:
    if arr[i]==0 and brr[i]==0:
        sm=(sm+(((m*(m-1))/2)%mod * pow((m*m),mod-2,mod))%mod * p)%mod
        p=(p*1*pow(m*m,mod-2,mod))%mod
    elif arr[i]==0:
        sm=(sm+((m-brr[i])%mod * pow(m,mod-2,mod))%mod * p)%mod
        p=(p*1*pow(m,mod-2,mod))%mod
    elif brr[i]==0:
        sm=(sm+((arr[i]-1)%mod * pow(m,mod-2,mod))%mod * p)%mod
        p=(p*1*pow(m,mod-2,mod))%mod
    else:
        if arr[i]<brr[i]:
            break
        elif arr[i]>brr[i]:
            sm=(sm + p)%mod
            break
    i=i+1
print sm


x=raw_input().split(' ')
n=int(x[0])
m=int(x[1])
y=raw_input().split(' ')
mod=1000000007
arr=[]
i=0
while i<n:
    arr.append(int(y[i]))
    i=i+1

y=raw_input().split(' ')
brr=[]
i=0
while i<n:
    brr.append(int(y[i]))
    i=i+1

i=0
p=1
sm=0
pm=pow(m,mod-2,mod)
pm2=pow((m*m),mod-2,mod)
while i<n:
    if arr[i]==0 and brr[i]==0:
        sm=(sm+((((m*(m-1))/2)%mod * pm2)%mod * p)%mod)%mod
        p=(p*m*pm2)%mod
    elif arr[i]==0:
        sm=(sm+(((m-brr[i])%mod * pm)%mod * p)%mod)%mod
        p=(p*1*pm)%mod
    elif brr[i]==0:
        sm=(sm+(((arr[i]-1)%mod * pm)%mod * p)%mod)%mod
        p=(p*1*pm)%mod
    else:
        if arr[i]<brr[i]:
            break
        elif arr[i]>brr[i]:
            sm=(sm + p)%mod
            break
    i=i+1
print sm


import sys
input = sys.stdin.readline

def main():
    tes = int(input())
    for testcase in [0]*tes:
        n,m = map(int,input().split())
        new = [True]*(3*n)
        res = []

        for i in range(1,m+1):
            u,v = map(int,input().split())
            if new[u-1] and new[v-1]:
                if len(res) < n:
                    res.append(i)
                    new[u-1] = new[v-1] = False

        if len(res) >= n:
            print("Matching")
            print(*res)
        else:
            vs = []
            for i in range(3*n):
                if new[i]:
                    vs.append(i+1)
                    if len(vs) >= n:
                        break
            print("IndSet")
            print(*vs)

if __name__ == '__main__':
    main()


import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)

def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))
import math

def prmatch(ans):
    print("Matching")
    print(*ans)

def solve():
    n, m = getList()
    # print("===================")
    # print(n, m)
    # print("----------------------")
    vertexes = [[] for i in range(3*n)]
    used = [0 for i in range(3*n)]
    ans = []
    lans = 0
    for i in range(m):
        a,b = getList()
        # print(a, b)
        if used[a-1] == 0 and used[b-1] == 0:
            ans.append(i+1)
            lans += 1
            if lans == n:
                prmatch(ans)
                for rem in range(m - i -1):
                    _ = input()
                return
            used[a-1] = 1
            used[b-1] = 1

    indset = []
    for i, u in enumerate(used):
        if u == 0:
            indset.append(i+1)

    print("IndSet")
    # print(ans)
    # print(used)
    print(*indset[:n])
    return

t = getN()
for times in range(t):
    solve()

"""
1
2 15
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
"""


# inspired by https://codeforces.com/contest/1198/submission/58086142

T = int(input())

for _ in range(T):
    n, m = map(int, input().split())
    v_count = 3*n
    verts = [[] for _ in range(v_count)]
    for k in range(m):
        v1, v2 = map(int, input().split())
        v1, v2 = min(v1, v2) - 1, max(v1, v2) - 1 # ?
        verts[v1].append((v2, k))

    MATCH = []
    IND = []
    DONE = [0]*v_count
    for i in range(v_count):
        if DONE[i]:
            continue
        for v, e in verts[i]:
            if DONE[v] == 0:
                MATCH.append(e+1)
                DONE[i] = 1
                DONE[v] = 1
                break
        else:
            IND.append(i+1)
            DONE[i] = 1

    if len(MATCH) >= n:
        print('Matching')
        print(*MATCH[:n])
    else:
        print('IndSet')
        print(*IND[:n])


# inspired by https://codeforces.com/contest/1198/submission/58086142

def main():
    T = int(input())

    v_cover = set()
    for _ in range(T):
        n, m = map(int, input().split())
        v_count = 3*n
        v_cover.clear()
        i_cover = []
        for k in range(m):
            edge = list(map(int, input().split()))
            if edge[0] not in v_cover and edge[1] not in v_cover:
                v_cover.add(edge[0])
                v_cover.add(edge[1])
                i_cover.append(k+1)
                if len(i_cover) == n:
                    print('Matching')
                    print(*i_cover[:n])
                    for _ in range(k+1, m):
                        input()
                    break

        if len(i_cover) < n:
            #v_independent = set(range(1, v_count+1)) - v_cover
            v_independent = []
            for vert in range(1, 3*n+1):
                if vert not in v_cover:
                    v_independent.append(vert)
                if len(v_independent) == n:
                    print('IndSet')
                    #print(*random.sample(v_independent, n))
                    print(*v_independent)
                    break

            if len(v_independent) < n:
                print('Impossible')

# preamble
import sys
input=sys.stdin.readline

# main call
if __name__== "__main__":
    main()


# inspired by https://codeforces.com/contest/1198/submission/58086142

def main():
    T = int(input())

    for _ in range(T):
        n, m = map(int, input().split())
        v_count = 3*n
        verts = [[] for _ in range(v_count)]
        for k in range(m):
            v1, v2 = map(int, input().split())
            v1, v2 = min(v1, v2) - 1, max(v1, v2) - 1 # ?
            verts[v1].append((v2, k))

        MATCH = []
        IND = []
        DONE = [0]*v_count
        for i in range(v_count):
            if DONE[i]:
                continue
            for v, e in verts[i]:
                if DONE[v] == 0:
                    MATCH.append(e+1)
                    DONE[i] = 1
                    DONE[v] = 1
                    break
            else:
                IND.append(i+1)
                DONE[i] = 1

        if len(MATCH) >= n:
            print('Matching')
            print(*MATCH[:n])
        else:
            print('IndSet')
            print(*IND[:n])

# preamble
import sys
input=sys.stdin.readline

# main call
if __name__== "__main__":
    main()


T = int(input())
for _ in range(T):
    n, m = map(int, input().split())
    v = set(range(1, 3 * n + 1))
    e = []
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if a in v and b in v:
            e.append(i)
            v.remove(a)
            v.remove(b)
    if len(e) >= n:
        print('Matching')
        print(*e[:n])
    else:
        print('IndSet')
        print(*list(v)[:n])


T = int(input())
for _ in range(T):
    n, m = map(int, input().split())
    v = [True] * (3 * n + 1)
    e = [0] * n
    ptr = 0
    ok = False
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if v[a] and v[b]:
            e[ptr] = i
            ptr += 1
            v[a] = False
            v[b] = False
        if ptr == n:
            print('Matching')
            print(*e)
            ok = True
            break
    if ok:
        continue
    print('IndSet')
    cnt = 0
    for i in range(1, n * 3 + 1):
        if v[i]:
            print(i, end=' ')
            cnt += 1
        if cnt == n:
            print()
            break


T = int(input())
v = [0] * (3 * 10 ** 5 + 1)
for t in range(1, T + 1):
    n, m = map(int, input().split())
    e = []
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if v[a] != t and v[b] != t:
            e.append(i)
            v[a] = t
            v[b] = t
    if len(e) >= n:
        print('Matching')
        print(*e[:n])
    else:
        print('IndSet')
        cnt = 0
        for i in range(1, n * 3 + 1):
            if v[i] != t:
                print(i, end=' ')
                cnt += 1
            if cnt == n:
                print()
                break


T = int(input())
for _ in range(T):
    n, m = map(int, input().split())
    v = [True] * (3 * n + 1)
    e = []
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if v[a] and v[b]:
            e.append(i)
            v[a] = False
            v[b] = False
    if len(e) >= n:
        print('Matching')
        print(*e[:n])
    else:
        print('IndSet')
        cnt = 0
        for i in range(1, n * 3 + 1):
            if v[i]:
                print(i, end=' ')
                cnt += 1
            if cnt == n:
                print()
                break


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
    n, m = map(int, input().split())
    v = set(range(1, 3 * n + 1))
    e = []
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if a in v and b in v:
            e.append(i)
            v.remove(a)
            v.remove(b)
    if len(e) >= n:
        print('Matching')
        print(*e[:n])
    else:
        print('IndSet')
        print(*list(v)[:n])


import sys
lines = iter(sys.stdin.readlines())

T = int(next(lines))
for _ in range(T):
    n, m = map(int, next(lines).split())
    v = set(range(1, 3 * n + 1))
    e = []
    for i in range(1, m + 1):
        a, b = map(int, next(lines).split())
        if a in v and b in v:
            e.append(i)
            v.remove(a)
            v.remove(b)
    if len(e) >= n:
        print('Matching')
        print(*e[:n])
    else:
        print('IndSet')
        print(*list(v)[:n])


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
    n, m = map(int, input().split())
    v = [True] * (3 * n + 1)
    e = [0] * n
    ptr = 0
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if ptr < n and v[a] and v[b]:
            e[ptr] = i
            ptr += 1
            v[a] = False
            v[b] = False
    if ptr == n:
        print('Matching')
        print(*e)
    else:
        print('IndSet')
        cnt = 0
        for i in range(1, n * 3 + 1):
            if v[i]:
                print(i, end=' ')
                cnt += 1
            if cnt == n:
                print()
                break


T = int(input())
for _ in range(T):
    n, m = map(int, input().split())
    v = [True] * (3 * n + 1)
    e = [0] * n
    ptr = 0
    ok = False
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if ok:
            continue
        if v[a] and v[b]:
            e[ptr] = i
            ptr += 1
            v[a] = False
            v[b] = False
        if ptr == n:
            print('Matching')
            print(*e)
            ok = True
    if ok:
        continue
    print('IndSet')
    cnt = 0
    for i in range(1, n * 3 + 1):
        if v[i]:
            print(i, end=' ')
            cnt += 1
        if cnt == n:
            print()
            break


T = int(input())
for _ in range(T):
    n, m = map(int, input().split())
    v = [True] * (3 * n + 1)
    e = [0] * n
    ptr = 0
    for i in range(1, m + 1):
        a, b = map(int, input().split())
        if ptr < n and v[a] and v[b]:
            e[ptr] = i
            ptr += 1
            v[a] = False
            v[b] = False
    if ptr == n:
        print('Matching')
        print(*e)
    else:
        print('IndSet')
        cnt = 0
        for i in range(1, n * 3 + 1):
            if v[i]:
                print(i, end=' ')
                cnt += 1
            if cnt == n:
                print()
                break


from sys import stdin

input = stdin.readline

def solve_graph():
    n,m = map(int, input().split())
    included = [False] + ([True]*(3*n))
    matching =[]
    for i in range(1,m+1):
        e1, e2 = map(int, input().split())
        if included[e1] and included[e2]:
            matching.append(i)
            included[e1] = False
            included[e2] = False
    if len(matching) >= n:
        print("Matching")
        print(*matching[:n])
        return
    intset = [x for (x,b) in enumerate(included) if b]
    print("IndSet")
    print(*(list(intset)[:n]))

t = int(input())
for _ in range(t):
    solve_graph()


from sys import stdin

input = stdin.readline

def solve_graph():
    n,m = map(int, input().split(max=1))
    included = [False] + ([True]*(3*n))
    matching =[]
    for i in range(1,m+1):
        e1, e2 = map(int, input().split(max=1))
        if included[e1] and included[e2]:
            matching.append(i)
            included[e1] = False
            included[e2] = False
    if len(matching) >= n:
        print("Matching")
        print(*matching[:n])
        return
    intset = [x for (x,b) in enumerate(included) if b]
    print("IndSet")
    print(*(list(intset)[:n]))

t = int(input())
for _ in range(t):
    solve_graph()


from sys import stdin, stdout

def input():
    return next(stdin)

def printnums(xs):
    output = " ".join(map((lambda x: str(x + 1)), xs)) + '\n'
    stdout.write(output)

def solve_graph():
    n,m = map(int, input().split())
    adj = [set() for _ in range(n*3)]
    excluded = set()
    matching =[]
    for i in range(m):
        e1, e2 = map(int, input().split())
        if e1 not in excluded and e2 not in excluded:
            matching.append(i)
            if len(matching) == n:
                for _ in range(i + 1, m):
                    input()
                stdout.write("Matching"+ '\n')
                printnums(matching)
                return
            excluded.add(e1)
            excluded.add(e2)
        adj[e1-1].add(e2-1)
        adj[e2-1].add(e1-1)
    adj = list(enumerate(adj))
    adj.sort(key=(lambda x: len(x[1])))
    excluded = set()
    indset = []
    for v,a in adj:
        if v not in excluded:
            indset.append(v)
            if len(indset) == n:
                stdout.write("IndSet"+'\n')
                printnums(indset)
                return
            excluded |= a
    print("Impossible")

t = int(input())
for _ in range(t):
    solve_graph()


from sys import stdin

input = stdin.readline

def solve_graph():
    n,m = map(int, input().split())
    excluded = [False]*(3*n+1)
    matching =[]
    for i in range(m):
        e1, e2 = map(int, input().split())
        if not excluded[e1] and not excluded[e2]:
            matching.append(i)
            if len(matching) == n:
                for _ in range(i + 1, m):
                    input()
                print("Matching")
                print(*map((lambda x: x + 1), matching))
                return
            excluded[e1] = True
            excluded[e2] = True
    intset = filter((lambda x: not excluded[x]), range(1,3*n+1))
    print("IndSet")
    print(*(list(intset)[:n]))

t = int(input())
for _ in range(t):
    solve_graph()


from sys import stdin, stdout

def input():
    return next(stdin)

def solve_graph():
    n,m = map(int, input().split())
    adj = [set() for _ in range(n*3)]
    if m >= n * (2 * n - 1):
        excluded = set()
        matching =[]
        for i in range(m):
            e1, e2 = map(int, input().split())
            if e1 not in excluded and e2 not in excluded:
                matching.append(i)
                if len(matching) == n:
                    for _ in range(i + 1, m):
                        input()
                    print("Matching")
                    print(*map((lambda x: x + 1), matching))
                    return
                excluded.add(e1)
                excluded.add(e2)
    else:
        for i in range(m):
            e1, e2 = map(int, input().split())
            adj[e1-1].add(e2-1)
            adj[e2-1].add(e1-1)
        adj = list(enumerate(adj))
        adj.sort(key=(lambda x: len(x[1])))
        excluded = set()
        indset = []
        for v,a in adj:
            if v not in excluded:
                indset.append(v)
                if len(indset) == n:
                    print("IndSet")
                    print(*map((lambda x: x + 1), indset))
                    return
                excluded |= a
    print("Impossible")

t = int(input())
for _ in range(t):
    solve_graph()


from sys import stdin

def input():
    return next(stdin)

def solve_graph():
    n,m = map(int, input().split())
    excluded = [False]*(3*n+1)
    matching =[]
    for i in range(m):
        e1, e2 = map(int, input().split())
        if not excluded[e1] and not excluded[e2]:
            matching.append(i)
            if len(matching) == n:
                for _ in range(i + 1, m):
                    input()
                print("Matching")
                print(*map((lambda x: x + 1), matching))
                return
            excluded[e1] = True
            excluded[e2] = True
    intset = filter((lambda x: not excluded[x]), range(1,3*n+1))
    print("IndSet")
    print(*(list(intset)[:n]))

t = int(input())
for _ in range(t):
    solve_graph()