Problem:


Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477



Sample input:
2 2


Sample output:
8

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    def make_factorial_table(size, mod):
        '''
        fact_mod[i] は i! % mod を表す。fact_mod[0] ~ facto_mod[size] まで計算可能なテーブルを返す
        >>> make_factorial_table(20, 10**9+7)
        [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 227020758, 178290591, 674358851, 789741546, 425606191, 660911389, 557316307, 146326063]
        '''
        fact_mod = [1] * (size + 1)
        for i in range(1, size + 1):
            fact_mod[i] = (fact_mod[i - 1] * i) % mod
        return fact_mod
    
    
    n, m = mi()
    n, m = min(n, m), max(n, m)
    fact = make_factorial_table(m, mod)

    if n == m-1:
        print((fact[m]*fact[n]) % mod)
    elif n == m:
        print((2*fact[m]*fact[n]) % mod)
    else:
        print(0)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
N,M = IL()

if N==M:
  print((2*kaijo(N)*kaijo(M))%MOD)
  E()
if abs(N-M) == 1:
  print((kaijo(N)*kaijo(M))%MOD)
  E()
PE(0)

Submission status: Accepted

Solution code:
from collections import Counter
from collections import deque
import math
import bisect
import sys
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

mod=1000000007
n,m=sorted(mp())
if m-n>1:
    ans=0
elif m-n==1:
    ans=m
    for i in range(1,n+1):
        ans*=i**2
        ans%=mod
else:
    ans=2
    for i in range(1,n+1):
        ans*=(i**2)
        ans%=mod
print(ans%mod)

Submission status: Accepted

Solution code:
from math import factorial as frac

N, M = map(int, input().split())

MOD = 10**9 + 7

def nPk(n, k):
    r = 1
    while k > 0:
        r *= n
        r %= MOD
        n -= 1
        k -=  1
    return r

if abs(N-M) > 1:
    print(0)
elif N==M:
    print(((nPk(N,N)*nPk(M,M))*2)%MOD)
else:
    print(nPk(N,N)*nPk(M,M)%MOD)

Submission status: Accepted

Solution code:
from math import factorial as frac

N, M = map(int, input().split())

INF = 10**9 + 7

if abs(N-M) > 1:
    print(0)
elif abs(N-M) == 1:
    print(frac(N)*frac(M)%INF)
else:
    print(((frac(N)*frac(M))*2)%INF)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())

MOD = 10 ** 9 + 7

if n == m:
    ans = 1
    for i in range(2, n + 1):
        ans = ans * i % MOD
    print(ans * ans * 2 % MOD)

elif n + 1 == m:
    ans = 1
    for i in range(2, n + 1):
        ans = ans * i % MOD
    print(ans * ans * m % MOD)

elif n == m + 1:
    ans = 1
    for i in range(2, m + 1):
        ans = ans * i % MOD
    print(ans * ans * n % MOD)

else:
    print(0)

Submission status: Accepted

Solution code:
import math
n, m = map(int, input().split())

if abs(n - m) > 1:
    print(0)
elif n == m:
    print(math.factorial(n) ** 2 * 2 % (pow(10, 9)+7))
else:
    print(math.factorial(n) * math.factorial(m) % (pow(10, 9)+7))

Submission status: Accepted

Solution code:
p = 10**9+7
N,M = map(int,input().split())
a = 1
for i in range(2,N+1):
    a = (a*i)%p
b = 1
for i in range(2,M+1):
    b = (b*i)%p
if M==N:
    n = (2*a*b)%p
elif M==N-1 or N==M-1:
    n = (a*b)%p
else:
    n = 0
print(n)

Submission status: Accepted

Solution code:
N,M=map(int,input().split())

if abs(N-M)>1:
    print(0)
    exit()

def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 10 ** 9 + 7
n = 10 ** 5  # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p) 階乗のmod
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用
 
for i in range(2, n + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

ans=(fact[N]*fact[M])%p
if N==M:
    ans*=2
    ans%=p
print(ans)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
mod=10**9+7
nkai=1
mkai=1
for i in range(1,n+1):
  nkai*=(i%mod)
  nkai=(nkai%mod)
for i in range(1,m+1):
  mkai*=(i%mod)
  mkai=(mkai%mod)
if abs(n-m)>=2:
  print(0)
elif abs(n-m)==1:
  print((mkai*nkai)%mod)
elif abs(n-m)==0:
  print((mkai*nkai*2)%mod)

Submission status: Accepted

Solution code:
import sys
MOD = pow(10,9)+7
N,M = map(int,input().split())
if N < M:
  N,M = M,N

if abs(N-M) >1 :
  print(0)
  sys.exit()
  
if N == M:
  ans = 2
  while N>0 and M>0:
    ans = ans*M*N%MOD
    M -= 1; N -= 1
else:
  if N == M:
    ans = 2
    while N>0 and M>0:
      ans = ans*M*N%MOD
      M -= 1; N -= 1
  else:
    ans = N
    N -= 1
    while N>0 and M>0:
      ans = ans*M*N%MOD
      M -= 1; N -= 1
print(ans)

Submission status: Accepted

Solution code:
def main():
    n,m = map(int,input().split())
    if abs(n-m) > 1:
        print(0)
    else:
        from math import factorial
        mod = 10**9+7
        res = factorial(n)*factorial(m)%mod
        if n == m:
            print(2*res%mod)
        else:
            print(res)
 
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

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


def resolve():
    n, m = map(int, input().split())

    if abs(n - m) >= 2:
        print(0)
        exit()

    fact = [1]
    for i in range(2, max(n, m) + 1):
        fact.append((fact[-1] * i) % mod)

    res = fact[n - 1] * fact[m - 1] % mod
    print(res if n != m else res * 2 % mod)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
MOD = 10 ** 9 + 7

N, M = map(int, input().split())

if abs(N - M) >= 2:
    print (0)
    exit()

class Factorial:
    def __init__(self, n, mod):
        self.f = [1]
        self.mod = mod
        for j in range(1, n + 1):
            self.f.append(self.f[-1] * j % mod)
        self.i = [pow(self.f[-1], mod - 2, mod)]
        for j in range(n, 0, -1):
            self.i.append(self.i[-1] * j % mod)
        self.i.reverse()
    def factorial(self, j):
        return self.f[j]
    def ifactorial(self, j):
        return self.i[j]
    def comb(self, n, k):
        return self.f[n] * self.i[n - k] % self.mod * self.i[k] % self.mod if n >= k else 0

#以下使い方

c = Factorial(max(N, M) + 2, MOD)

n = c.factorial(N)
m = c.factorial(M)

if (N == M):
    ans = 2 * n * m % MOD
else:
    ans = n * m % MOD

print (ans)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
delta = abs(n - m)

mod = 10 ** 9 + 7
N = 10 ** 5 + 5
bikkuri = [0 for i in range(N)]
bikkuri[0] = 1
gyaku = [0 for i in range(N)]
gyaku[0] = 1
for i in range(1, N):
    bikkuri[i] = (i * bikkuri[i - 1]) % mod
    gyaku[i] = pow(bikkuri[i], mod - 2, mod)

if delta > 1:
    print(0)
else:
    if n > m:
        ans = bikkuri[n] * bikkuri[m]
    elif m > n:
        ans = bikkuri[m] * bikkuri[n]
    else:
        ans = 2 * bikkuri[m] * bikkuri[n]
    print(ans % mod)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/abc065/tasks/arc076_a

# 0のとき abs(N-M)>1 必ず隣り合うところができてしまう
# それ以外のとき、Nの順列×Mの順列×犬と猿の並べ方
# 並べ方→同数→×2
# 異なる場合→×1

N, M = read_ints()
if abs(N - M) > 1:
    print(0)
    exit()

N_per = 1
M_per = 1
for i in range(1, N + 1):
    N_per *= i
    N_per %= MOD

for i in range(1, M + 1):
    M_per *= i
    M_per %= MOD


print((2 if N == M else 1) * N_per * M_per % MOD)

Submission status: Accepted

Solution code:
import math

N, M = map(int, input().split())
Q = int(1e9 + 7)

if max(N, M) - min(N, M) > 1:
    print(0)
else:
    if N == M:
        ans = math.factorial(N)
        ans %= Q
        ans *= math.factorial(M)
        ans %= Q
        ans *= 2
        ans %= Q
    else:
        ans = math.factorial(N)
        ans %= Q
        ans *= math.factorial(M)
        ans %= Q
    print(ans)

Submission status: Accepted

Solution code:
import math
N, M = map(int, input().split())

if abs(N - M) >= 2:
    ans = 0

elif N == M:
    ans = 2 * math.factorial(N) * math.factorial(M)

elif abs(N - M) == 1:
    ans = math.factorial(N) * math.factorial(M)

print(ans % (10**9 + 7))

Submission status: Accepted

Solution code:
import math;
f=math.factorial;
n,m=sorted(map(int,input().split()));
print(max(2-m+n,0)*f(n)*f(m)%(10**9+7))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
mod = 10**9+7

if abs(n-m)>1:
    print(0)
else:
    ans=1
    for i in range(1,n+1):
        ans=ans*i%mod
    for j in range(1,m+1):
        ans=ans*j%mod
    if n==m:
        ans=ans*2%mod
    print(ans)

Submission status: Accepted

Solution code:
from functools import reduce

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

if abs(n - m) >= 2:
    print(0)
elif abs(n - m) == 1:
    a = reduce(lambda x, y: (x * y) % mod, range(1, n + 1))
    b = reduce(lambda x, y: (x * y) % mod, range(1, m + 1))
    ans = (a * b) % mod
    print(ans)
elif n == m:
    c = reduce(lambda x, y: (x * y) % mod, range(1, n + 1))
    ans = (c*c * 2) % mod
    print(ans)

Submission status: Accepted

Solution code:
import math;f=math.factorial;n,m=sorted(map(int,input().split()));print(max(2-m+n,0)*f(n)*f(m)%(10**9+7))

Submission status: Accepted

Solution code:
import math
MOD = 10**9+7
f = math.factorial
n, m = sorted(map(int, input().split()))
print(max(2 - m + n, 0)*f(n)*f(m) % MOD)

Submission status: Accepted

Solution code:
import math
def myAnswer(N:int,M:int) -> int:
   if(abs(N - M) >= 2): return 0
   ans = 0
   if(abs(N - M) == 1):
      ans = math.factorial(N) * math.factorial(M)
   else:
      ans = math.factorial(N) ** 2 * 2

   return ans % (10**9 + 7)

def modelAnswer():
   return
def main():
   N,M = map(int,input().split())
   print(myAnswer(N,M))
if __name__ == '__main__':
   main()

Submission status: Accepted

Solution code:
def factorial(x, mod=10**9+7):
    # x!
    # 階乗
    # ex) factorial(5) = 120
    tmp = 1
    for i in range(1, x+1):
        tmp = (tmp * i) % mod
    return tmp


N ,M = map(int, input().split())
mod = 1000000007

if N==M:
    print((2*factorial(N)**2) % mod )
elif abs(N-M)==1:
    print((factorial(N)*factorial(M))%mod)
else:
    print(0)

Submission status: Accepted

Solution code:
import math
N, M = map(int, input().split())
mod = 10**9 + 7
if abs(N-M) >= 2:
    print(0)
    exit()
elif N == M:
    print(2*(math.factorial(N)**2) % mod)
else:
    print(math.factorial(N)*math.factorial(M) % mod)

Submission status: Accepted

Solution code:
import math
n,m = map(int,input().split())

if 2 <= abs(n-m):
    print (0)
elif 1 == abs(n-m):
    print ((math.factorial(n)*math.factorial(m))%((10**9)+7))
elif n == m:
    print ((2*(math.factorial(n)*math.factorial(m)))%((10**9)+7))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
if abs(N - M) > 1:
    print(0)
    exit()
mod = 10 ** 9 + 7
ans = 1
for i in range(1, N + 1):
    ans = ans * i % mod
for i in range(1, M + 1):
    ans = ans * i % mod
print(ans * 2 % mod if N == M else ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import re
import math
from collections import defaultdict
from collections import deque
import collections
from fractions import Fraction
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
#@lru_cache(maxsize=None)
readline=sys.stdin.readline
sys.setrecursionlimit(2000000)
#import numpy as np
alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def ispow(a,b):#aはbの累乗数か
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def pm(x):
    return x//abs(x)
def inputintlist():
    return list(map(int,input().split()))
######################################################################################################

n,m=inputintlist()
llen=n+m
facs=getfacs(n+m+1,mod)
if abs(n-m)>1:
    print(0)
elif abs(n-m)==1:
    cnt=facs[n]*facs[m]
    cnt%=mod
    print(cnt)
else:
    cnt=facs[n]*facs[m]
    cnt*=2
    cnt%=mod
    print(cnt)

Submission status: Accepted

Solution code:
from math import factorial
n,m = map(int,input().split())
if abs(n-m) > 1:
  print(0)
elif n == m:
  ans = 2*(factorial(n)%(10**9+7))**2%(10**9+7)
  print(ans)
else:
  ans = (factorial(n)%(10**9+7))*(factorial(m)%(10**9+7))%(10**9+7)
  print(ans)

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
mod = 10**9+7
def mod_f(i):
    ans = 1
    for i in range(1,i+1):
        ans *= i
        ans %= mod
    return ans

if abs(n-m) > 1:
    print(0)
elif n == m:
    print((mod_f(n)*mod_f(m)*2)%mod)
else:
    print((mod_f(n)*mod_f(m))%mod)

Submission status: Accepted

Solution code:
from math import factorial

N, M = map(int, input().split())
mod = 10**9+7

if abs(N-M) > 1:
    print(0)
    quit()

else:
    if N == M:
        #犬猿or猿犬をひとかたまりとして考える。
        NM_half = N
        #犬猿どっちが右かを区別する
        ans = 2
        # ans %= mod 
        #個別の犬、猿がどこに立つかを考慮する
        ans *= factorial(N)
        ans %= mod
        ans *= factorial(M)
        ans %= mod

        print(ans)
    else:
        ans = factorial(N)
        ans %= mod
        ans *= factorial(M)
        ans %= mod

        print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    def COMinit(n,MOD):
        fac,finv,inv=[0]*max(2,n+1),[0]*max(2,n+1),[0]*max(2,n+1)
        fac[0]=fac[1]=1
        finv[0]=finv[1]=1
        inv[1]=1
        for i in range(2,(n+1)):
            fac[i]=fac[i-1]*i%MOD
            inv[i]=MOD-inv[MOD%i]*(MOD//i)%MOD
            finv[i]=finv[i-1]*inv[i]%MOD
        return fac,finv,inv
    
    fac,finv,inv=COMinit(10**5,MOD)
    
    def COM(n, k, MOD=MOD):
        if n<k or n<0 or k<0:
            return 0
        return fac[n]*(finv[k]*finv[n-k]%MOD)%MOD
    
    
    N,M=map(int,input().split())
    if abs(N-M)==0:
        print(fac[N]*fac[M]*2%MOD)
    elif abs(N-M)==1:
        print(fac[N]*fac[M]%MOD)
    else:
        print(0)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
N,M=map(int,input().split())
d=abs(N-M)
if d>1:
  print(0)
elif d==1:
  ans=math.factorial(N)*math.factorial(M)%(10**9+7)
  print(ans)
else:
  ans=math.factorial(N)*math.factorial(M)*2%(10**9+7)
  print(ans)

Submission status: Accepted

Solution code:
import math
def main():
    Dog, Mon = map(int, input().split())
    comb = 0

    if Dog > Mon:
        if Dog > Mon + 1:
            pass
        else:
            comb = (math.factorial(Dog) * math.factorial(Mon)) % (10**9+7)

    elif Dog == Mon:
        comb = (math.factorial(Dog) * math.factorial(Mon) * 2) % (10**9+7)
    else:
        if Mon -1 > Dog:
            pass
        else:
            comb = (math.factorial(Dog) * math.factorial(Mon)) % (10**9+7)

    print(comb)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import math

def f(n):
    if n==1:
        return 1
    return n*f(n-1)

N,M = map(int, input().split())

if abs(N-M)>=2:
    print(0)
elif abs(N-M)==1:
    print(math.factorial(N)*math.factorial(M)%(10**9+7))
else:
    print((2*math.factorial(N)*math.factorial(M))%(10**9+7))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
MOD = 10**9+7
d = abs(N-M)
if d > 1:
    print(0)
else:
    ans = 1
    for i in range((N+M)//2):
        ans *= (N-i)*(M-i)
        ans %= MOD
    if (N+M) % 2 == 0:
        ans *= 2
    print(ans % MOD)

Submission status: Accepted

Solution code:
import math
N,M = map(int,input().split())
if(abs(N - M) >= 2):
  print("0")
else:
  if(N != M):
    print(str(((math.factorial(N) * math.factorial(M)) % (10 ** 9 + 7))))
  else:
    print(str(((math.factorial(N) * math.factorial(M))* 2 % (10 ** 9 + 7))))

Submission status: Accepted

Solution code:
import math
n, m = map(int, input().split())
 
N = math.factorial(n)
M = math.factorial(m)
INF = 10**9 + 7
 
if abs(n-m) > 1:
    print(0)
elif abs(n-m) == 1:
    print(N*M%INF)
else:
    print(2*N*M%INF)

Submission status: Accepted

Solution code:
import math
n,m=map(int,input().split())
if abs(n-m)>=2:
    print(0)
else:
    if abs(n-m)==1:
        print(math.factorial(n)%(10**9+7)*math.factorial(m)%(10**9+7))
    else:
        print(2*(math.factorial(n))**2%(10**9+7))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 13:07:12 2020

@author: shinba
"""

import sys
sys.setrecursionlimit(10**7)
 
def patikaijou(n):
    if n == 0:
        return 1
    else:
        return (n*patikaijou(n-1))%(10**9+7)

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

if abs(n-m) >= 2:
    print(0)
elif n != m:
    print((patikaijou(n)*patikaijou(m))%(10**9+7))
else:
    print((2*((patikaijou(n))**2))%(10**9+7))

Submission status: Accepted

Solution code:
from math import pow

MOD = int(pow(10, 9)) + 7


class ModFactorial:
    def __init__(self, n):
        self._table = [0] * (n + 1)
        self._table[0] = 1
        for i in range(1, n + 1):
            self._table[i] = mod_mul(self._table[i - 1], i)

    def factorial(self, n):
        return self._table[n]


def mod_mul(n, m):
    return n * m % MOD


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

if abs(N - M) > 1:
    print(0)
else:
    f = ModFactorial(max(N, M))
    c = mod_mul(f.factorial(N), f.factorial(M))

    if N == M:
        c = mod_mul(c, 2)

    print(c)

Submission status: Accepted

Solution code:
n, m = map(int,input().split())
ans = 1
if abs(n-m) == 0:
    for i in range(1,n+1):
       ans *= i
       ans = ans%(10**9+7)
    ans = 2*(ans**2)
    print(ans%(10**9+7))
    


elif abs(n-m) == 1:
    for i in range(1,min(n+1,m+1)):
        ans *= i
        ans = ans%(10**9+7)
    ans = max(n,m)*(ans**2)
    print(ans%(10**9+7))


else:
    print(0)

Submission status: Accepted

Solution code:
def factorial(n):
    res = 1
    while n > 0:
        res = (res*n)%mod
        n -= 1
    return res

n, m = map(int, input().split())
mod = 10**9 + 7
if abs(n-m) >= 2:
    print(0)
    exit()
ans = (factorial(min(n,m))%mod)**2 * max(n,m) if n != m else 2*(factorial(min(n,m))%mod)**2
print(ans%mod)

Submission status: Accepted

Solution code:
def main():
    from math import factorial
    n, m = map(int, input().split())
    n, m = max(n, m), min(n, m)
    mod = 10 ** 9 + 7
    if -1 <= n - m <= 1:
        ans = factorial(n) % mod
        ans *= (-n + m + 2) * factorial(m)
        ans %= mod
        print(ans)
    else:
        print(0)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
d = 10 ** 9 + 7


def factorial(n):
    ans = 1
    for q in range(1, n + 1):
        ans *= q
        if ans >= d:
            ans %= d
    return ans


if abs(n - m) > 1:
    print(0)
    exit(0)

if n == m:
    ans = ((factorial(n) % d) ** 2) * 2 % d
if n != m:
    ans = factorial(n) * factorial(m) % d
print(ans)

Submission status: Accepted

Solution code:
def fact(n):
    mod = int(1e9)+7
    res = 1
    for i in range(1,n+1):
        res = (res*i)%mod
    return res

N,M = map(int,input().split())

if abs(N-M) >= 2:
    print(0)
    exit()

mod = int(1e9)+7

if N == M:
    print(2*fact(N)*fact(M)%mod)
else:
    print(fact(N)*fact(M)%mod)

Submission status: Accepted

Solution code:
import math
f=math.factorial
n,m=map(int,input().split())
print(f(n)*f(m)*(1+(n==m))%(10**9+7) if abs(n-m)<2 else 0)

Submission status: Accepted

Solution code:
import math
N,M = map(int,input().split())

if abs(N-M) >= 2:
    print(0)
    exit()
sum = 1
count = 0
if N == M:
    sum *= N+M
    sum *= int(((N+M)/2))
    N = int((N+M)/2)-1
    M = N
else:
    sum *= max(N,M)

k = math.factorial(min(N,M))
sum *= k**2

print(sum%(10**9+7))