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

import sys
from io import StringIO
import unittest

def resolve():
    n = int(input())
    s = input()
    ans = 0
    r_cnt = s.count('R')
    g_cnt = s.count('G')
    g_cnt = s.count('G')

    for i in range(n):
        for j in range(1, n - i, 1):
            if s[i] != s[i+j]:
                for x in ('R', 'G', 'B'):
                    if x not in (s[i], s[i+j]):
                        tmp = x
                if i+2*j < n and s[i+2*j] == tmp:
                    ans += s[i+j+1:].count(tmp) - 1
                else:
                    ans += s[i+j+1:].count(tmp)

    print(ans)


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """4
RRGB"""
        output = """1"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB"""
        output = """1800"""
        self.assertIO(input, output)

if __name__ == "__main__":
    #unittest.main()
    resolve()

### FIXED CODE ###

import sys
from io import StringIO
import unittest

def resolve():
    n = int(input())
    s = input()
    ans = s.count('R') * s.count('G') * s.count('B')

    for i in range(n):
        for j in range(1, (n - 1)//2 + 1, 1):
            if i + 2 * j < n:
                if s[i] != s[i + j] and s[i] != s[i + 2 * j] and s[i + j] != s[i + 2 * j]:
                    ans -= 1

    print(ans)


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """4
RRGB"""
        output = """1"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB"""
        output = """1800"""
        self.assertIO(input, output)

if __name__ == "__main__":
    #unittest.main()
    resolve()
### BUGGY CODE ###

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

for i in range(1, N+1):
    print(la.count(i))

### FIXED CODE ###

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

la.append(N+1)

lb = [0] * N
for i in range(N-1):
    lb[la[i]-1] += 1

for j in range(N):
    print(lb[j])
### BUGGY CODE ###

a,b,k = list(map(int, input().split()))
count = 1
for i in range(a, b+1):
  if(i < a+k or  b-k < i):
    print(i)

### FIXED CODE ###

a,b,k = list(map(int, input().split()))
if(b-a <= 200):
  for i in range(a, b+1):
    if(i < a + k or b - k < i):
      print(i)
else:
  for i in range(a, a+k):
    print(i)
  for i in range(b-k+1, b+1):
    print(i)
### BUGGY CODE ###

N, M, K =map(int, input().split())
A = list(map(int, input().split()))
A.insert(0,0)
B = list(map(int, input().split()))  
B.insert(0,0)
len_A = len(A)
len_B = len(B)
dp = [[0]*len_B for _ in range(len_A)]
ans = 0
for i in range(len_A):
    for j in range(len_B):
        if i == 0 and j == 0:
            dp[i][j] = 0
        elif i == 0:
            dp[i][j] = dp[i][j-1] + B[j]
            if dp[i][j] <= K and ans < i+j :
                ans = i+j
        else:
            dp[i][j] = dp[i-1][j] + A[i]
            if dp[i][j] <= K and ans < i+j :
                ans = i+j

print(ans)

### FIXED CODE ###

N, M, K =map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))  
sum_A = [0]
sum_B = [0]
for a in range(len(A)):
    sum_A.append(sum_A[a]+A[a])

for b in range(len(B)):
    sum_B.append(sum_B[b]+B[b])

len_A = len(sum_A)
j = len(sum_B) - 1
ans = 0
for i in range(len_A):
    a = sum_A[i]
    while True:
        if j < 0:
            break
        if a + sum_B[j] <= K:
            ans = max(ans,i + j)
            break
        j -= 1
    if j < 0:
        break

print(ans)
### BUGGY CODE ###

N = int(input())
A = list(map(int,input().split()))
B =[]
i = N-1
M = 0
while(i>=0):
    sum1=0
    j = i + i
    while (j<N):
        sum1 += 1
        j+=i
    if sum1%2!=A[i]:
        M+=1
        B.append(i)
    i-=1
B.reverse
print(M)
for s in B:
    print(s,end=" ")

### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))
B = [0 for i in range(N)]
i = N

j = 0
while i>0:
    sum1=0
    j = i + i
    while j<=N:
        sum1 += B[j-1]
        sum1=(sum1+2)%2
        j=j+i
    B[i-1]+=(A[i-1]+sum1)
    B[i-1]=(B[i-1]+2)%2
    i=i-1
count=0
for s in B:
  if s == 1 :
    count+=1
print(count)
for i in range(N):
  if B[i]==1:
    print(i+1,end=" ")
### BUGGY CODE ###

import fractions as m
from functools import reduce
n = int(input())
a = list(map(int,input().split()))
ans = 0
mod = 10**9+7
def lcm(x,y):
    return (x*y//m.gcd(x,y))
def lcml(nums):
    return reduce(lcm,nums,1)
l = lcml(a)
for x in a:
    ans+= (l*pow(x,mod-2,mod)) %mod
    ans%=mod
print(ans)

### FIXED CODE ###

import fractions as m
from functools import reduce
n = int(input())
a = list(map(int,input().split()))
ans = 0
mod = 10**9+7
def lcm(x,y):
    return (x*y//m.gcd(x,y))
def lcml(nums):
    return reduce(lcm,nums,1)
l = lcml(a)
for x in a:
    ans+= (l*pow(x,mod-2,mod)) %mod
    ans%=mod
print(ans)
### BUGGY CODE ###

import sys
import copy
n=int(input())
a=[]
for i in range(n):
  a.append(list(map(int,input().split())))
maxmatch=n*(n-1)
day=0
q=[i for i in range(n)]
nq=[]
match=[0]*(n+1)
check=[0]*(n+1)
while q:
  day+=1
  for i in q:
    if match[i]==n-1 or check[i]==day:
      continue
    else:
      vs=a[i][match[i]]-1
      if check[vs]!=day and check[i]!=day and a[vs][match[vs]]-1==i and a[i][match[i]]-1==vs:
        match[i]+=1
        match[vs]+=1
        match[n]+=2
        check[i]=day
        check[vs]=day
        check[n]=day
        nq.append(i)
        nq.append(vs)
      
    if i==q[-1]:
      if check[n]!=day:
        print(-1)
        sys.exit()
  if match[n]==maxmatch:
    break
  q=copy.copy(nq)
  nq=[]
        
print(day)


### FIXED CODE ###

import sys
MAX_INT = int(10e9)
MIN_NUM = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()
 
N = I()
a = [IL()[::-1] for i in range(N)]
 
used = [-1]*N
updatelist = [i for i in range(N)]
total = N*(N-1)//2
cnt = 0
days = 0
ul = []
while updatelist:
  ul = []
  for i in updatelist:
    #print(a)
    #print(i+1)
    if len(a[i]) > 0 and used[i] != days:
      numIND = a[i][-1] -1
      #print(numIND+1)
      if a[numIND][-1] == i+1 and used[numIND] != days:
        a[i].pop(-1)
        a[numIND].pop(-1)
        used[i] = days
        used[numIND] = days
        ul.append(i)
        ul.append(numIND)
        cnt += 1
  else:
    updatelist = ul[:]
    if len(ul) != 0:
      days += 1
#print(a)
#print(cnt)
if cnt == total:
  print(days)
else:
  print(-1)
### BUGGY CODE ###

import sys
from functools import lru_cache
sys.setrecursionlimit(10**8)

lmax = lambda x, y: x if len(x) > len(y) else y
dp = dict()

@lru_cache(maxsize=10000)
def lcs(x,y):
    if x == "" or y == "":
        return ""
    elif x[-1] == y[-1]:
        return lcs(x[:-1],y[:-1]) + x[-1]
    else:
        return lmax(lcs(x[:-1],y), lcs(x,y[:-1]))

print(lcs(input(),input()))

### FIXED CODE ###

S,T = input(),input()
x,y = len(S),len(T)

dp = [[0]*(y+1) for _ in range(x+1)]

for i,s in enumerate(S):
  for j,t in enumerate(T):
    dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j], dp[i][j] + int(s==t))
    
a = ""
while x > 0 and y > 0:
  if dp[x][y] == dp[x-1][y]:
    x -= 1
  elif dp[x][y] == dp[x][y-1]:
    y -= 1
  else:
    x -= 1
    y -= 1
    a += S[x]

print(a[::-1])
### BUGGY CODE ###

# -*- coding: utf-8 -*-
n = int(input())
t = []
a = []
for _ in range(n):
    line = input().split(" ")
    t.append(int(line[0]))
    a.append(int(line[1]))

T = t[0]
A = a[0]

for i in range(1,n):
    c = 1
    tt = t[i]
    aa = a[i]
    while T>tt or A>aa:
        c += 1
        tt = t[i]*c
        aa = a[i]*c
    T = tt
    A = aa

print(T+A)


### FIXED CODE ###

# -*- coding: utf-8 -*-
import math
n = int(input())
T = 1
A = 1
for _ in range(n):
    line = input().split(" ")
    t = int(line[0])
    a = int(line[1])
    c = max((T+t-1)//t, (A+a-1)//a)
    T = c*t
    A = c*a

print(A+T)
### BUGGY CODE ###

n = int(input())
a = list(map(int,input().split()))
b = []
c = [[] for _ in range(n)]

def make_divisors(n):
	lower_divisors , upper_divisors = [], []
	i = 1
	while i*i <= n:
		if n % i == 0:
			lower_divisors.append(i)
			if i != n // i:
				upper_divisors.append(n//i)
		i += 1
	return lower_divisors + upper_divisors[::-1]

#半分より上は, すべてa通り.
for i in range(1,n+1)[::-1]:
	if len(c[i-1]) % 2 != a[i-1]:
		b.append(i)
		for j in make_divisors(i):
			c[j-1].append(0)
print(len(b))
print(" ".join(list(map(str, b))))

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))
b = []
c = [0 for _ in range(n)]

def make_divisors(n):
	lower_divisors , upper_divisors = [], []
	i = 1
	while i*i <= n:
		if n % i == 0:
			lower_divisors.append(i)
			if i != n // i:
				upper_divisors.append(n//i)
		i += 1
	return lower_divisors + upper_divisors[::-1]

#半分より上は, すべてa通り.
for i in range(1,n+1)[::-1]:
	if c[i-1] % 2 != a[i-1]:
		b.append(i)
		for j in make_divisors(i):
			c[j-1] += 1
print(len(b))
print(" ".join(list(map(str, b))))
### BUGGY CODE ###

import numpy as np
def main():
    N, M, Q = map(int, input().split())
    LR = []
    for i in range(M):
        l, r = map(int, input().split())
        LR.append([l-1, r])
    PQ = []
    for i in range(Q):
        p, q = map(int, input().split())
        PQ.append([p-1, q-1])
    ar = np.zeros([M, N])
    for m in range(M):
        ar[m, LR[m][0]:LR[m][1]] = 1
    flags_start = [np.ones(M, dtype=np.bool)]
    flags_end = []
    for i in range(1, N):
        flags_start.append((ar[:, :i].max(axis=1)==0))# * (ar[:, i:].max(axis=1)==1))
        flags_end.append((ar[:, i:].max(axis=1)==0))# * (ar[:, :i].max(axis=1)==1))
    flags_end.append(np.ones(M, dtype=np.bool))
    for q in range(Q):
        left = PQ[q][0]
        right = PQ[q][1]
        print(sum(flags_start[left] * flags_end[right]))

if __name__=='__main__':
    main()

### FIXED CODE ###

import numpy as np
N, M, Q = map(int, input().split())
LR = []
for i in range(M):
    l, r = map(int, input().split())
    LR.append([l, r])
PQ = []
for i in range(Q):
    p, q = map(int, input().split())
    PQ.append([p, q])
ar_sec = np.zeros([N, N])
for i in range(M):
    l, r = LR[i][0], LR[i][1]
    ar_sec[l-1][r-1] += 1


ar_sum = np.zeros([N+1, N+1])
for i in range(N):
    for j in range(N):
        ar_sum[i+1][j+1] = ar_sum[i][j+1]+ar_sum[i+1][j]-ar_sum[i][j]+ar_sec[i][j]

for i in range(Q):
    p, q = PQ[i][0], PQ[i][1]
    print(int(ar_sum[q][q]-ar_sum[p-1][q]))
### BUGGY CODE ###

def main():
    import sys
    sys.setrecursionlimit(10**5)
    N = int(input())
    a = list(map(int, input().split()))
    A = [0]*4
    for x in a:
        A[x] += 1

    dp = [[[0]*(N+1) for i in range(N+1)] for j in range(N+1)]

    for k in range(A[3]+1):
        for j in range(A[2]+A[3] + 1 - k):
            for i in range(A[1]+A[2]+A[3] + 1 - k - j):
                if i == 0 and j == 0 and k == 0:
                    continue
                P = N
                if i > 0:
                    P += dp[i-1][j][k] * i
                if j > 0:
                    P += dp[i+1][j-1][k] * j
                if k > 0:
                    P += dp[i][j+1][k-1] * k
                dp[i][j][k] = P/(i+j+k)

    print(dp[A[1]][A[2]][A[3]])


main()


### FIXED CODE ###

def main():
    N = int(input())
    A = list(map(int, input().split()))
    a = A.count(1)
    b = A.count(2)
    c = A.count(3)
    floatN = N*1.0
    dp = [[[.0]*(N+1) for i in range(N+1)] for j in range(N+1)]

    for k in range(c+1):
        for j in range(b+c + 1 - k):
            for i in range(N + 1 - k - j):
                if i + j+k == 0:
                    continue
                dp[i][j][k] = floatN
                if i > 0:
                    dp[i][j][k] += dp[i-1][j][k] * i
                if j > 0:
                    dp[i][j][k] += dp[i+1][j-1][k] * j
                if k > 0:
                    dp[i][j][k] += dp[i][j+1][k-1] * k
                dp[i][j][k] /= (i+j+k)
    print(dp[a][b][c])


main()
### BUGGY CODE ###

import sys
from math import sqrt
input = sys.stdin.readline
N = int(input())
e = []
for _ in range(N):
  x, y = map(int, input().split())
  e.append((x, y))
t = pow(10, 5) * 5
res = 0
for a in range(2):
  for b in range(2):
    xbias = (-1) ** a
    ybias = (-1) ** b
    for u in range(t + 1):
      v = sqrt(t ** 2 - u ** 2) * ybias
      px = 0
      py = 0
      for i in range(N):
        x, y = e[i]
        if u * x * xbias + v * y * ybias > 0:
          px += x
          py += y
      res = max(res, sqrt(px ** 2 + py ** 2))
print(res)

### FIXED CODE ###

import sys
from math import sqrt
input = sys.stdin.readline
N = int(input())
e = []
for _ in range(N):
  x, y = map(int, input().split())
  e.append((x, y))
res = 0
for i in range(N):
  for j in range(N):
    u = e[i][0] + e[j][0]
    v = e[i][1] + e[j][1]
    px = 0
    py = 0
    for k in range(N):
      x, y = e[k]
      if u * x + v * y > 0:
        px += x
        py += y
    res = max(res, sqrt(px ** 2 + py ** 2))
print(res)
### BUGGY CODE ###

class UnionFind():
    def __init__(self, n):
        self._n = n
        self._table = [-1]*n
        self._rank = [0]*n

    def _root(self, x):
        stack = []
        while self._table[x] >= 0:
            stack.append(x)
            x = self._table[x]
        for y in stack:
            self._table[y] = x
        return x
    
    def unite(self, x, y):
        x, y = self._root(x), self._root(y)
        if x == y:
            return
        elif self._rank[x] > self._rank[y]:
            self._table[x] += self._table[y]
            self._table[y] = x
        else:
            self._table[y] += self._table[x]
            self._table[x] = y
            if self._rank[x] == self._rank[y]:
                self._rank[y] += 1
    
    def find(self, x, y):
        return self._root(x) == self._root(y)

    def count(self, x):
        return -self._table[self._root(x)]
    
    def __str__(self):
        return str(list(self))
    def __repr__(self):           
        return repr(list(self))
    def __iter__(self):
        return (self._root(i) for i in range(n))
    def __list__(self):
        return list(iter(self))

n, m, *X = map(int, open(0).read().split())
P, XY = X[:n], X[n:]

uf = UnionFind(n)
for x, y in zip(XY[::2], XY[1::2]):
    uf.unite(x-1, y-1)
group = list(uf)
ans = 0
for i in set(group):
    L = {j for j, n in enumerate(group, 1) if n == i}
    R = {P[l-1] for l in L}
    ans += len(L & R)
print(ans)

### FIXED CODE ###

class UnionFind():
    def __init__(self, n):
        self._n = n
        self._table = [-1]*n
        self._rank = [0]*n

    def _root(self, x):
        stack = []
        while self._table[x] >= 0:
            stack.append(x)
            x = self._table[x]
        for y in stack:
            self._table[y] = x
        return x
    
    def unite(self, x, y):
        x, y = self._root(x), self._root(y)
        if x == y:
            return
        elif self._rank[x] > self._rank[y]:
            self._table[x] += self._table[y]
            self._table[y] = x
        else:
            self._table[y] += self._table[x]
            self._table[x] = y
            if self._rank[x] == self._rank[y]:
                self._rank[y] += 1
    
    def find(self, x, y):
        return self._root(x) == self._root(y)

    def count(self, x):
        return -self._table[self._root(x)]
    
    def __str__(self):
        return str(list(self))
    def __repr__(self):           
        return repr(list(self))
    def __iter__(self):
        return (self._root(i) for i in range(n))
    def __list__(self):
        return list(iter(self))

from collections import defaultdict
n, m, *X = map(int, open(0).read().split())
P, XY = X[:n], X[n:]

uf = UnionFind(n)
for x, y in zip(XY[::2], XY[1::2]):
    uf.unite(x-1, y-1)
group = list(uf)

d1 = defaultdict(set)
d2 = defaultdict(set)
for i, n in enumerate(group, 1):
    d1[n].add(i)
    d2[n].add(P[i-1])

ans = 0
for i in set(group):
    ans += len(d1[i] & d2[i])
print(ans)
### BUGGY CODE ###

a, b = map(int, input().split())

def calc(n):
    lst = []
    
    if n%4==1 or n%4==2:lst.append('1')
    else:lst.append('0')
      
    m = 1
    while n//2**m!=0:
        l = n%2**(m+1)
        if l >= 2**m and l%2==0:
            lst.append('1')
        else:lst.append('0')
        m += 1
    lst.append('0b')
    lst.reverse()
    
    return ''.join(lst)

lsta = int(calc(a-1),0)
lstb = int(calc(b),0)
print(lsta^lstb)


### FIXED CODE ###

a, b = map(int, input().split())

def calc(n):
    lst = []
    if n==-1:return '0b0'
    if n%4==1 or n%4==2:lst.append('1')
    else:lst.append('0')
      
    mm = 2
    
    while n//mm != 0:
        l = n%(2*mm)
        if l >= mm and l%2==0:
            lst.append('1')
        else:lst.append('0')
        mm *= 2
    lst.append('0b')
    lst.reverse()
    return ''.join(lst)

lsta = int(calc(a-1),0)
lstb = int(calc(b),0)

print(lsta^lstb)
### BUGGY CODE ###

N , K = map(int, input().split())
h = list(map(int, input().split()))

Dp = [None]*N
Dp[0] = 0
Dp[1] = abs(h[1]-h[0])

for i in range(2,N):
  Dp[i] =min([Dp[j]+abs(h[i]-h[j]) for j in range(max(0,i-K),i)])

print(Dp[-1])


### FIXED CODE ###

N , K = map(int, input().split())
h = list(map(int, input().split()))

Dp = [None]*N
Dp[0] = 0

for i in range(1,N):
  Dp[i] =min([Dp[j]+abs(h[i]-h[j]) for j in range(max(0,i-K),i)])

print(Dp[-1])
### BUGGY CODE ###

n = int(input())
s = list(input())
pin_li = []
for i in range(len(s)):
    for j in range(i+1,len(s)):
        for k in range(j+1,len(s)):
            pin_li.append(s[i]+s[j]+s[k])
            if len(set(pin_li)) > 1000:
                break
print(len(set(pin_li)))

### FIXED CODE ###

n = int(input())
s = input()
cnt = 0
for i in range(1000):
    p = '{:03}'.format(i)
    s2 = s
    for j in range(3):#indexのループ
        if s2.find(p[j]) == -1:
            break
        s2 = s2[s2.find(p[j]) +1:]
    else:
        cnt+=1
print(cnt)
### BUGGY CODE ###

import math
from functools import reduce

n = int(input())
def gcd(*numbers):
    return reduce(math.gcd, numbers)

c = 0
for i in range(n):
    for j in range(n):
        for k in range(n):
            c += gcd(i+1,j+1,k+1)

print(c)

### FIXED CODE ###

import math
# from functools import reduce
# from fractions import gcd
def main():
    n = int(input())
    # def gcd(*numbers):
    #     return reduce(math.gcd, numbers)

    c = 0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                temp = math.gcd(i+1,j+1)
                c += math.gcd(temp,k+1)

    print(c)

main()
### BUGGY CODE ###

N = int(input())
a = []
for i in range(3):
    a.append(list(map(int, input().split())))

for i in range(3):
    a[i].sort()

dataa = []
datab = []
memo = 0
for i in range(N):
    flag = 0
    for j in range(memo, N):
        if a[0][i] < a[1][j]:
            memo = j
            dataa.append(N - j)
            flag = 1
            break
    if flag == 0:
        dataa.append(0)
memo = 0
for i in range(N):
    flag = 0
    for j in range(memo, N):
        if a[1][i] < a[2][j]:
            memo = j
            datab.append(N - j)
            flag = 1
            break
    if flag == 0:
        datab.append(0)
ruiseki = []
count = 0
for i in range(len(datab)-1, -1, -1):
    count += datab[i]
    ruiseki.append(count)
count2 = 0
for i in range(len(dataa)):
    if dataa[i] != 0:
        count2 += ruiseki[dataa[i] - 1]



print(count2)


### FIXED CODE ###

N = int(input())
a = []
for i in range(3):
    a.append(list(map(int, input().split())))

for i in range(3):
    a[i].sort()

dataa = []
datab = []
memo = 0
#print(a)
for i in range(N):
    flag = 0
    for j in range(memo, N):
        #print(a[0][i], a[1][j])
        if a[0][i] < a[1][j]:
            memo = j
            dataa.append(N - j)
            flag = 1
            break
    if flag == 0:
        for j in range(N - i):
            dataa.append(0)
        break
memo = 0
for i in range(N):
    flag = 0
    for j in range(memo, N):
        if a[1][i] < a[2][j]:
            memo = j
            datab.append(N - j)
            flag = 1
            break
    if flag == 0:
        for j in range(N - i):
            datab.append(0)
        break
ruiseki = []
count = 0
for i in range(len(datab)-1, -1, -1):
    count += datab[i]
    ruiseki.append(count)
count2 = 0
for i in range(len(dataa)):
    if dataa[i] != 0:
        count2 += ruiseki[dataa[i] - 1]



print(count2)
### BUGGY CODE ###

N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))

# 早期終了

if len(set(A)) != len(A):
    print(0)
    exit()
if len(set(B)) != len(B):
    print(0)
    exit()

# 高速化のため事前ソート

A.sort(reverse=True)
B.sort(reverse=True)


def ret_n_given_x(x):
    flgA = True if x in A else False
    flgB = True if x in B else False
    # print(flgA, flgB)
    if flgA and flgB:
        return 1
    elif flgA:
        ret = 0
        for b in B:
            if x <= b:
                ret += 1
            else:
                break
        return ret
    elif flgB:
        ret = 0
        for a in A:
            if x <= a:
                ret += 1
            else:
                break
        return ret
    else:
        retb = 0
        for b in B:
            if x <= b:
                retb += 1
            else:
                break
        reta = 0
        for a in A:
            if x <= a:
                reta += 1
            else:
                break
        return (retb * reta)-(N*M-x)


MOD = 10**9 + 7
ans = 1
for x in range(N * M, 0, -1):
    ans *= ret_n_given_x(x)
    ans %= MOD
    # print(x, ans, ret_n_given_x(x))
    if ans == 0:
        break

print(int(ans))


### FIXED CODE ###

N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))

# 早期終了

if len(set(A)) != len(A):
    print(0)
    exit()
if len(set(B)) != len(B):
    print(0)
    exit()

# 高速化のため事前ソート

A.sort(reverse=True)
B.sort(reverse=True)

n_A, n_B = 0, 0  # ある数よりも大きい要素数(単調増加)
# この問題は場合分けを思いつけるか、計算量を減らせるかにかかっている
# 与えられた集合の中にxょり大きい要素がいくつあるかという処理に大きく時間がかかっている
# これをn_Aとおくと、n_Aには単調増加性があることがすぐにわかる
# xをどんどん小さくしているからである。
# n_Aを逐一計算する代わりに、いままでの情報を使ってn_Aを求められると処理が高速化される
# A=[182, 181, 180, 179, 178, 176, 175, 169, 168, 167, 158, 151, 147, 129]とする(sorted)とすると、
# A[n_A]=xとなるn_Aがほしい。xが登場するまでのイテレーションでx_pre in Aとなる要素があるたび、その回数をカウントすればよい
#


def ret_n_given_x(x):
    global n_A, n_B
    flgA = False
    flgB = False
    for a in A[n_A:]:
        if a == x:
            flgA = True
            break
    for a in B[n_B:]:
        if a == x:
            flgB = True
            break
    if flgA and flgB:
        n_A += 1  # 上記で解説した個数カウント
        n_B += 1  # xより大きな要素が何個あったかついでに記録できる
        return 1
    elif flgA:
        n_A += 1
        return n_B
    elif flgB:
        n_B += 1
        return n_A
    else:
        return (n_A * n_B)-(N*M-x)


MOD = 10**9 + 7
ans = 1
for x in range(N * M, 0, -1):
    ans *= ret_n_given_x(x)
    ans %= MOD
    # print(x, ans, ret_n_given_x(x))
    if ans == 0:
        break

print(int(ans))