Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

from itertools import groupby, accumulate, product, permutations, combinations
from bisect import *
def calc(A,p,q):
  ind = bisect_right(A,p/2+q)
  M = min(A[ind]-q,A[-1]-A[ind-1])
  if ind==0:
    M = A[ind]-q
  m = p - M
  return M,m
def solve():
  ans = float('inf')
  N = int(input())
  A = list(map(int, input().split()))
  cum = list(accumulate(A))
  for i in range(1,N-2):
    mae = cum[i]
    usiro = cum[-1]-cum[i]
    lis = [*calc(cum[:i+1],mae,0),*calc(cum[i+1:],usiro,cum[i])]
    ans = min(ans,max(lis)-min(lis))
  return ans
print(solve())

### FIXED CODE ###

from itertools import groupby, accumulate, product, permutations, combinations
from bisect import *
def solve():
  ans = float('inf')
  N = int(input())
  A = list(map(int, input().split()))
  cum = list(accumulate(A))
  for i in range(1,N-2):
    mae = cum[i]
    usiro = cum[-1]-cum[i]
    ind = bisect_right(cum,mae/2)
    mae_max = min(cum[ind],mae-cum[ind-1])
    if ind==0:
      mae_max = cum[ind]
    mae_min = mae - mae_max
    ind2 = bisect_right(cum,usiro/2+cum[i])
    usiro_max = min(cum[ind2]-cum[i],cum[-1]-cum[ind2-1])
    if ind2==i+1:
      usiro_max = cum[ind2]-cum[i]
    usiro_min = usiro - usiro_max
    lis = [mae_max,mae_min,usiro_max,usiro_min]
    ans = min(ans,max(lis)-min(lis))
  return ans
print(solve())
### BUGGY CODE ###

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


L=[str(a.index(i)+1) for i in range(1,n+1)]
L=" ".join(L)
print(L)

### FIXED CODE ###

from operator import itemgetter
n=int(input())
a=list(map(int,input().split()))

print(*[t[0] +1 for t in sorted(enumerate(a),key=itemgetter(1))])
### BUGGY CODE ###

# coding: utf-8
import sys
sysread = sys.stdin.readline
from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**6)
def run():
    N,M,K = map(int,sysread().split())
    to = [[] for _ in range(N+1)]
    n_to = [0 for _ in range(N + 1)]
    for i in range(1,M+1):
        a,b = map(int, sysread().split())
        to[a].append(b)
        n_to[a] += 1
        to[b].append(a)
        n_to[b] += 1

    stack = defaultdict(lambda:[])
    visited = [False] * (N+1)
    belong = [None] * (N+1)

    def dfs(n, tree= None):
        visited[n] = True
        if tree==None:
            tree = n
        stack[tree].append(n)
        belong[n] = tree
        for next in to[n]:
            if not visited[next]:
                dfs(next, tree)
        return None

    while True:
        k = -1
        for i in range(1,N+1):
            if not visited[i]:
                k = i
                break
        if k == -1:break
        dfs(k)

    block = [0 for _ in range(N+1)]
    for i in range(1, K+1):
        c,d = map(int, sysread().split())
        if belong[c] == belong[d]:
            block[c] += 1
            block[d] += 1

    candidates = [0] * (N+1)

    for tree in stack.keys():
        length = len(stack[tree])
        for k in stack[tree]:
            candidates[k] = length - 1 - n_to[k] - block[k]

    print(' '.join(map(str, candidates[1:])))

if __name__ == "__main__":
    run()

### FIXED CODE ###

# coding: utf-8
import sys
sysread = sys.stdin.readline
from collections import defaultdict
sys.setrecursionlimit(10**7)
def run():

    N,M,K = map(int,sysread().split())
    to = [[] for _ in range(N+1)]
    n_to = [0 for _ in range(N + 1)]
    for i in range(1,M+1):
        a,b = map(int, sysread().split())
        #a,b = AB[i]
        to[a].append(b)
        n_to[a] += 1
        to[b].append(a)
        n_to[b] += 1

    stack = defaultdict(lambda:0)
    visited = [False] * (N+1)
    belong = [None] * (N+1)


    def dfs(n):
        _stack = [n]
        visited[n] = True
        while _stack:
            node = _stack.pop()
            stack[n] += 1
            belong[node] = n
            for next in to[node]:
                if not visited[next]:
                    _stack.append(next)
                    visited[next] = True
        return None


    for i in range(1,N+1):
        if not visited[i]:
            dfs(i)

    block = [0 for _ in range(N+1)]
    for i in range(1, K+1):
        c,d = map(int, sysread().split())
        #c, d = CD[i]
        if belong[c] == belong[d]:
            block[c] += 1
            block[d] += 1

    candidates = [0] * (N+1)

    for k in range(1,N+1):
        tr = belong[k]
        candidates[k] = stack[tr] - 1 - n_to[k] - block[k]

    print(' '.join(map(str, candidates[1:])))

if __name__ == "__main__":
    run()
### BUGGY CODE ###

def knapsack_rec(target, W, V): # target=knapsack weight
    P = {}
    P[target] = 0 # default + max

    for vi in range(len(V)):
        we = W[vi]
        va = V[vi]
        for i in range(we, target + 1):
            if i in P:
                prev = P.get(i - we, -1)
                if prev < P[i] + va:
                    P[i - we] = P[i] + va

    return max(P.values())

assert knapsack_rec(15, [6, 5, 6, 6, 3, 7], [5, 6, 4, 6, 5, 2]) == 17

if __name__ == "__main__":
    import sys
    n, w, *r = map(int, sys.stdin.read().split())
    W, V = r[::2], r[1::2]
    ans = knapsack_rec(w, W, V)
    print(ans)


### FIXED CODE ###

def knapsack_rec(target, W, V): # target=knapsack weight
    P = {}
    P[0] = target
    max_ = 0

    for vi in range(len(V)):
        we, va = W[vi], V[vi]
        for i in range(max_, -1, -1):
            if i in P:
                piva = P.get(i + va, -1)
                if piva < P[i] - we:
                    P[i + va] = P[i] - we
                    if max_ < i + va:
                        max_ = i + va
    return max_

assert knapsack_rec(15, [6, 5, 6, 6, 3, 7], [5, 6, 4, 6, 5, 2]) == 17

if __name__ == "__main__":
    import sys
    n, w, *r = map(int, sys.stdin.read().split())
    W, V = r[::2], r[1::2]
    ans = knapsack_rec(w, W, V)
    print(ans)
### BUGGY CODE ###


cnt = 0
n = int(input())
a = list(map(int, input().split()))

for i in range(0,n-1,1):
    for o in range(i+1,n,2):
        if a[i]+a[o] == o-i:
            cnt += 1
        if (o+1 <= n-1) and (a[i]+a[o+1] == o+1-i):
            cnt += 1

print(cnt)

### FIXED CODE ###


from collections import defaultdict

n = int(input())
a = list(map(int, input().split()))
lInfo = defaultdict(int)
rInfo = defaultdict(int)
cnt = 0

for i in range(n):
    lInfo[a[i]+i] += 1
    rInfo[i-a[i]] += 1

for k in lInfo.keys():
    cnt += lInfo[k] * rInfo[k]
print(cnt)
### BUGGY CODE ###

M,z,s=998244353,1,0
d=[1]+[0]*7**6
e=[1]+[0]*7**6
for _ in'_'*input():
 a=input();s+=a;i=s;z*=3
 while~i:d[i]+=d[i]+d[i-a]%M;e[i]+=e[i-a];i-=1
i=s
while i*2>=s:z-=d[i]*3;i-=1
print(z+~s%2*e[s//2]*3)%M

### FIXED CODE ###

M,z,s=998244353,1,0
N,*A=map(int,open(0))
d=[1]+[0]*7**6
e=[1]+[0]*7**6
for a in A:
 i=s;s+=a;z*=3
 while~i:d[i+a]+=d[i]%M;d[i]*=2;e[i+a]+=e[i]%M;i-=1
i=s
while i*2>=s:z=(z-d[i]*3)%M;i-=1
print((z+~s%2*e[s//2]*3)%M)
### BUGGY CODE ###


N, M, K = map(int, input().rstrip().split(' '))

comb = [0] * (N * M + 1)
comb[K-2] = 1
for i in range(K-1, N*M+1):
    comb[i] = comb[i-1] * i // (i - (K - 2))

cost = 0
for d in range(1, N):
    cost += d * M**2 * (N - d) * comb[N*M-2]# comb[(N-d-1)*M]
    cost %= 1000000007
for d in range(1, M):
    cost += d * N**2 * (M - d) * comb[N*M-2]# comb[(M-d-1)*N]
    cost %= 1000000007
    
print(cost)



### FIXED CODE ###


import math

def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

N, M, K = map(int, input().rstrip().split(' '))

comb = cmb(N*M-2, K-2) % 1000000007

cost = 0
for d in range(1, N):
    cost += d * M**2 * (N - d) * comb
    cost %= 1000000007
for d in range(1, M):
    cost += d * N**2 * (M - d) * comb
    cost %= 1000000007
    
print(cost)
### BUGGY CODE ###

a,b,x=[int(i) for i in input().split()]
count=0
for i in range(a,b+1):
    if(i%x==0):
        count+=1
print(count)


### FIXED CODE ###

a,b,x=[int(i) for i in input().split()]
print(b//x-(a-1)//x)
### BUGGY CODE ###

n, m = list(map(int, input().split()))
a = [0]* n
b = [0]* n
for i in range(n):
    a[i], b[i] = list(map(int, input().split()))

ans = 0

for j in range(1,m+1):
    # aがj以下で最大のbをもつもの
    bmax = 0
    bmaxind = n
    for i in range(n):
        if a[i] <= j and b[i] > bmax:
            bmax = b[i]
            bmaxind = i
    ans += bmax
    if bmaxind < n:
        a[bmaxind] = float('inf')
    
print(ans)

### FIXED CODE ###

import heapq

# max heap
class Heapq:
    def __init__(self, arr, desc=False):
        if desc:
            arr = [-a for a in arr]
        self.sign = -1 if desc else 1
        self.hq = arr
        heapq.heapify(self.hq)
 
    def pop(self):
        return heapq.heappop(self.hq) * self.sign
 
    def push(self, a):
        heapq.heappush(self.hq, a * self.sign)
 
    def top(self):
        return self.hq[0] * self.sign
 
    def size(self):
        return len(self.hq)

from collections import defaultdict
d = defaultdict(list)

n, m = map(int, input().split())
ab = [tuple(map(int,input().split())) for i in range(n)]
for a,b in ab:
    d[a].append(b)

q = Heapq([], True)
 
ans = 0
for i in range(1,m+1):
    for b in d[i]:
        q.push(b)
    if q.size():
        ans += q.pop()
print(ans)
### BUGGY CODE ###

n = int(input())
n_list = list(map(int, input().split()))

multi = 1

for i in range(n):
    multi = multi*n_list[i]

if multi<=1e18:
    print(multi)
else:
    print(-1)
     


### FIXED CODE ###

n = int(input())
n_list = list(map(int, input().split()))

multi = 1
a = 1

for i in range(n):
    if n_list[i]==0:
        a = 0
        break

for i in range(n):
    if a == 0:
        multi = 0
        break

    multi *= n_list[i]

    if multi>1e18:
        break

if multi<=1e18:
    print(multi)
else:
    print(-1)
### BUGGY CODE ###

n = int(input())
s = input()

ans = n
for i in range(1,n):
  w = s[:i - 1].count('W')
  e = s[i:].count('E')
  ans = min(ans,w+e)
  
print(ans)

### FIXED CODE ###

n = int(input())
s = input()

w = 0
e = s.count('E')
ans = s.count('E')
for i in range(n):
  if i:
    if s[i - 1] == 'W':
      w += 1
  if s[i] == 'E':
    e -= 1
  ans = min(ans,w + e)
    
print(ans)
### BUGGY CODE ###

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

def kouyaku(n,p):
    for i in range(round((p**(1/n)+1)),0,-1):
        if p%i==0:
            if p%(i**n)==0:
                return i
            
print(kouyaku(n,p))

### FIXED CODE ###

N, P = map(int, input().split())
ans = 1
 
if N >= 45:
  print(ans)
elif N == 1:
  print(P)
  
 
  
else:
  i = 1
  while(i**N <= P):
    if P % (i**N) == 0:
      ans = i
    i += 1
  print(ans)
### BUGGY CODE ###

n = int(input())
dat = list(map(int, input().split()))
buf = [0] * (n+1)
buf.append(0)
cur = 0
for i in range(0, n):
    cur += dat[i]
    buf[i+1] = cur

#print(buf)

res = 0
for i in range(0, n+1):
    for j in range(i + 1, n+1):
        if buf[i] == buf[j]:
            res += 1
print(res)


### FIXED CODE ###

# k = 1 - nまでの k の和
def sigma1(n):
    return n * (n + 1) // 2

n = int(input())
dat = list(map(int, input().split()))
buf = [0] * (n+1)
cur = 0
import collections
pos = collections.defaultdict(list)

for i in range(0, n):
    cur += dat[i]
    pos[cur].append(i)
    buf[i+1] = cur

buf.sort()
#print(buf)
import collections
res = 0
c = collections.Counter(buf)
for k in c.keys():
    cnt = c[k]
    if cnt < 2:
        pass
    else:
        res += sigma1(cnt - 1)
print(res)
### BUGGY CODE ###

#i文字目を見て，それより前のAの個数，ABの個数，ABCの個数を持っておく

S=input()
N=len(S)
dp=[0,0,0]

mod=10**9+7


count=0#?の数
for i in range(N):
    if S[i]=="A":
        dp[0]=(dp[0]+pow(3,count)) %mod
    elif S[i]=="B":
        dp[1]=(dp[1]+dp[0])%mod
    elif S[i]=="C":
        dp[2]=(dp[2]+dp[1])%mod
    else:
        dp[2]=(dp[2]*3+dp[1])%mod
        dp[1]=(dp[1]*3+dp[0])%mod
        dp[0]=(dp[0]*3+pow(3,count))%mod
        count+=1
        
print(dp[2]%mod)   







### FIXED CODE ###

#i文字目を見て，それより前のAの個数，ABの個数，ABCの個数を持っておく

S=input()
N=len(S)
dp=[0,0,0]

mod=10**9+7

p=[1]*(N+1)
for i in range(N):
    p[i+1]=(p[i]*3)%mod


count=0#?の数
for i in range(N):
    if S[i]=="A":
        dp[0]=(dp[0]+p[count]) %mod
    elif S[i]=="B":
        dp[1]=(dp[1]+dp[0])%mod
    elif S[i]=="C":
        dp[2]=(dp[2]+dp[1])%mod
    else:
        dp[2]=(dp[2]*3+dp[1])%mod
        dp[1]=(dp[1]*3+dp[0])%mod
        dp[0]=(dp[0]*3+p[count])%mod
        count+=1
        
print(dp[2]%mod)
### BUGGY CODE ###

N=int(input())
*A,=sorted(map(int,input().split()))
*B,=sorted(map(int,input().split()))
*C,=sorted(map(int,input().split()))
from bisect import *

cnt=0
for a in A:
    in_b = bisect_right(B, a)
    for b in B[in_b:]:
        in_c = bisect_right(C, b)
        for c in C[in_c:]:
            cnt+=1
print(cnt)

### FIXED CODE ###

N=int(input())
*A,=sorted(map(int,input().split()))
*B,=sorted(map(int,input().split()))
*C,=sorted(map(int,input().split()))

lenc=len(C)

from bisect import *

cnt=0
for b in B:
    in_a = bisect_left(A, b)
    in_c = bisect_right(C, b)
    cnt+= in_a*(lenc-in_c)

print(cnt)
### BUGGY CODE ###

def gcd(a, b):
    if a%b==0: return b
    return gcd(b, a%b)
K=int(input())
sum=0
for a in range(1,K+1):
    for b in range(1,K+1):
        for c in range(1,K+1):
            sum+=gcd(gcd(a,b),c)
print(sum)

### FIXED CODE ###

import math
def gcd(a,b,c):
    return math.gcd(math.gcd(a,b),c)
K=int(input())
sum=0
for a in range(1,K+1):
    for b in range(a,K+1):
        for c in range(b,K+1):
            if a==b==c: sum+=a
            elif a!=b!=c: sum+=gcd(a,b,c)*6 
            else: sum+=gcd(a,b,c)*3
print(sum)
### BUGGY CODE ###

from numpy import*
N,T,*L=int_(open(0).read().split())
d=[0]*6010
for w,v in sorted(zip(*[iter(L)]*2)):d[w:T+w]=maximum(d[w:T+w],d[:T]+v)
print(max(d))

### FIXED CODE ###

N, T, *AB = map(int, open(0).read().split())

dp = [0] * (T + max(AB[::2]))
for w, v in sorted(zip(*[iter(AB)] * 2)):
    for i in reversed(range(T)):
        dp[i + w] = max(dp[i + w], dp[i] + v)

print(max(dp))
### BUGGY CODE ###

N = int(input())
b = list(map(int, input().split()))

def dfs(c):
  if len(c) == 0:
    return []

  for i in range(1, len(c)+1):
    if c[i-1] == i:
      cc = c.copy()
      del cc[i-1]
      res = dfs(cc)
      if res is not False:
        res.append(i)
        return res
  return False

res = dfs(b)
if res is False:
  print(-1)
else:
  for i in res:
    print(i)

### FIXED CODE ###

N = int(input())
b = list(map(int, input().split()))

def dfs(c):
  if len(c) == 0:
    return []

  for i in range(len(c), 0, -1):
    if c[i-1] > i:
      return False

    if c[i-1] == i:
      cc = c.copy()
      del cc[i-1]
      res = dfs(cc)
      if res is not False:
        res.append(i)
        return res

  return False

res = dfs(b)
if res is False:
  print(-1)
else:
  for i in res:
    print(i)
### BUGGY CODE ###

n, m = map(int, input().split())
a = []
b = [[] for i in range(n)]
for i in range(m):
	p, y = map(int, input().split())
	a.append([p,y])
	b[p-1].append(y)

for i, j in a:
	b[i-1].sort()
	x = b[i-1].index(j)
	print ("{:06d}".format(i) + "{:06d}".format(x+1))

### FIXED CODE ###

n, m = map(int, input().split())
a = []
b = [[] for i in range(n)]
for i in range(m):
	p, y = map(int, input().split())
	a.append([p,y])
	b[p-1].append(y)
dic = {}
for i in range(n):
	b[i].sort()
	for j,k in enumerate(b[i]):
		dic[k] = j+1

for i, j in a:
	print ("{:06d}".format(i) + "{:06d}".format(dic[j]))
### BUGGY CODE ###

import math

n, a, b = map(int, input().split())
mod = 10 ** 9 + 7

ans = 0

p = 2


def cmb(n, r):
    if n - r < r:
        r = n - r
    if r == 0:
        return 1
    if r == 1:
        return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2, r + 1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p - 1, r, p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result


for i in range(int(math.sqrt(n))):
    p *= p % mod

if n % 2 == 1:
    p *= 2

ans = p % mod - 1
ans -= cmb(n, a)
ans -= cmb(n, b)


print(int(ans % mod))


### FIXED CODE ###

from sys import setrecursionlimit

setrecursionlimit(2 * 10 ** 9)

n, a, b = map(int, input().split())
mod = 10 ** 9 + 7

ans = pow(2, n, mod) - 1


def cmb(n, r):
    p, q = 1, 1
    for i in range(1, r + 1):
        p *= (n - i + 1)
        p %= mod
        q *= i
        q %= mod
    return p * pow(q, mod - 2, mod)


ans -= cmb(n, a)
ans -= cmb(n, b)


print(int(ans % mod))
### BUGGY CODE ###

s=input()
t=input()

dp=[[0]*(len(t)+1) for _ in range(len(s)+1)]
ans=[[[-1,0,0] for _ in range(len(t)+1)] for _ in range(len(s)+1)]

for i,c in enumerate(s):
    for j,d in enumerate(t):
        if c==d:
            dp[i+1][j+1]=dp[i][j]+1
            ans[i+1][j+1]=[i,i,j]
        else:
            dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j])
            ans[i+1][j+1]=ans[i][j+1] if dp[i+1][j+1]==dp[i][j+1] else ans[i+1][j]

i=len(s)
j=len(t)
ss=['']*dp[i][j]
l=dp[i][j]-1
while i>0 and j>0:
    x,i,j=ans[i][j]
    if x>-1:
        ss[l]=s[x]
        l-=1

print(''.join(ss))


### FIXED CODE ###

s=input()
t=input()

dp=[[0]*(len(t)+1) for _ in range(len(s)+1)]
ans=[[(-1,-1) for _ in range(len(t)+1)] for _ in range(len(s)+1)]

for i,c in enumerate(s):
    for j,d in enumerate(t):
        if c==d:
            dp[i+1][j+1]=dp[i][j]+1
            ans[i+1][j+1]=(i,j)
        else:
            dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j])
            ans[i+1][j+1]=ans[i][j+1] if dp[i+1][j+1]==dp[i][j+1] else ans[i+1][j]

i=len(s)
j=len(t)
ss=['']*dp[i][j]
l=dp[i][j]-1
while i>0 and j>0:
    i,j=ans[i][j]
    if i>-1:
        ss[l]=s[i]
        l-=1

print(''.join(ss))
### BUGGY CODE ###

a = int(input())

b = input().split(" ")
score = 1

for i in range(a):
  t = int(b[i])
  score *= t
  
if score > 10 ** 18:
  print(-1)
else:
  print(score)

### FIXED CODE ###

a1 = int(input())
b2 = input().split(" ")

def check(a , b):
  score = 1
  if '0' in b:
    return 0
  else:
    for i in range(a):
      score *= int(b[i])
      if score > 10 ** 18:
        return -1
    
    return score

print(check(a1 , b2))
### BUGGY CODE ###

import collections
n=int(input())
s=sorted([input() for k in range(n)])
s1=list(set(s))
c=collections.Counter(s)
p=[]
for i in range(len(s1)):
    p.append(c[s1[i]])
c=collections.Counter(p)
ans=[j for j, x in enumerate(p) if x == max(p)]
y=[]
for o in ans:
    y.append(s1[o])
y=sorted(y)
for m in range(len(y)):
    print(y[m])

### FIXED CODE ###

N = int(input())
d = {}
for _ in range(N):
  s = input()
  if(s not in d):
    d[s] = 1
  else:
    d[s] += 1
d2 = sorted(d.items(),key=lambda x:x[1], reverse=True)
s1=[]
s1.append(d2[0][0])
p=d2[0][1]
for t in d2[1:]:
  q=t[1]
  if(q==p):
    s1.append(t[0])
  else:
    break
s1=sorted(s1)
for i in s1:
  print(i)
### BUGGY CODE ###

import sys
from bisect import bisect_left

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, m = map(int, input().split())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    if len(A) != len(set(A)) or len(B) != len(set(B)):
        print(0)
        exit()
    A.sort()
    B.sort()
    As = set(A)
    Bs = set(B)
    res = 1
    for x in reversed(range(1, n * m + 1)):
        if x in As and x in Bs:
            continue
        elif x in A:
            res *= m - bisect_left(B, x)
        elif x in B:
            res *= n - bisect_left(A, x)
        else:
            s = m - bisect_left(B, x)
            t = n - bisect_left(A, x)
            res *= s * t - (n * m - x)
        res %= mod
    print(res)


if __name__ == '__main__':
    resolve()


### FIXED CODE ###

import sys
from bisect import bisect_left

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, m = map(int, input().split())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    if len(A) != len(set(A)) or len(B) != len(set(B)):
        print(0)
        exit()
    A.sort()
    B.sort()
    As = set(A)
    Bs = set(B)
    res = 1
    for x in reversed(range(1, n * m + 1)):
        if x in As and x in Bs:
            continue
        elif x in A:
            res *= m - bisect_left(B, x)
        elif x in B:
            res *= n - bisect_left(A, x)
        else:
            s = m - bisect_left(B, x)
            t = n - bisect_left(A, x)
            res *= s * t - (n * m - x)
        res %= mod
    print(res)


if __name__ == '__main__':
    resolve()
### BUGGY CODE ###

s = input()

count = 0
removed = True
while removed:
    removed = False
    for i in range(1, len(s)):
        if s[i-1] != s[i]:
            s = s[0:i-1] + s[i+1:]
            removed = True
            count += 2
            break
print(count)


### FIXED CODE ###

s = input()
ans = min(s.count('1'), s.count('0')) * 2
print(ans)
### BUGGY CODE ###

import sys
input = sys.stdin.readline


def main():
    N, K = map(int, input().split())
    p = list(map(int, input().split()))
    answer = 0
    sum_list = [sum(p[:i]) for i in range(N+1)]
    for i in range(N-K+1):
        answer = max(answer, sum_list[i+K]-sum_list[i])
    print((answer+K)/2)


if __name__ == '__main__':
    main()


### FIXED CODE ###

import sys
input = sys.stdin.readline


def main():
    N, K = map(int, input().split())
    p = list(map(int, input().split()))
    answer = sum(p[0:K])
    r = answer
    for i in range(N-K):
        answer = answer - p[i] + p[i+K]
        r = max(r, answer)
    print((r+K)/2)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

K, S = map(int, input().split())

r = range(K+1)

counter = 0
for x in r:
    for y in r:
        z = S - x - y
        if 0 <= z <= K and x + y + z == S:
            counter += 1
print(counter)


### FIXED CODE ###

K, S = map(int, input().split())

counter = 0
for x in range(K+1):
    for y in range(K+1):
        z = S - x - y
        if 0 <= z <= K:
            counter += 1
print(counter)
### BUGGY CODE ###

import string


lowercase = string.ascii_lowercase

s = input()
K = int(input())

substrings = ['']

for i in range(K):
    for c in lowercase:
        for string in substrings:
            if string+c in s and string+c not in substrings:
                substrings.append(string+c)

print(sorted(substrings)[K])


### FIXED CODE ###

import string


lowercase = string.ascii_lowercase

s = input()
K = int(input())

substrings = []

stack = list(lowercase)[::-1]

while len(substrings) < K:
    # print(stack)
    v = stack.pop()
    if v in s:
        substrings.append(v)
        for c in list(lowercase)[::-1]:
            stack.append(v+c)

print(substrings[K-1])