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: Runtime Error

Solution code:
import sys
#import time
import copy
#from collections import deque, Counter, defaultdict
#from fractions import gcd
#import bisect
#import heapq
#import time

input = sys.stdin.readline
sys.setrecursionlimit(10**8)
inf = 10**18
MOD = 1000000007
ri = lambda : int(input())
rs = lambda : input().strip()
rl = lambda : list(map(int, input().split()))

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.rnk = [0]*(n+1)

    # ノードxのrootノードを見つける
    def find(self, x):
        if(self.root[x] < 0):
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if(x == y):
            return 
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def same(self, x, y):
        return self.find(x) == self.find(y)
    # ノードxが属する木のサイズを返す
    def size(self, x):
        return -self.root[self.find(x)]


n = ri()
d1=[tuple(rl())+tuple((i,)) for i in range(n)]
d2=d1[:]

d1.sort(key=lambda x:x[0])
d2.sort(key=lambda x:x[1])
edge=[]
for i in range(n-1):
    edge.append((d1[i+1][2], d1[i][2],d1[i+1][0]-d1[i][0]))
    edge.append((d2[i+1][2], d2[i][2],d2[i+1][1]-d2[i][1]))


    
edge.sort(key=lambda x: x[2])
res=0
uf = UnionFind(n)
for e in edge:
    if uf.same(e[0], e[1]):
        continue
    uf.unite(e[0], e[1])
    res+=e[2]
print(res)

Submission status: Runtime Error

Solution code:
import sys
#import time
import copy
#from collections import deque, Counter, defaultdict
#from fractions import gcd
#import bisect
#import heapq
#import time

input = sys.stdin.readline
sys.setrecursionlimit(10**8)
inf = 10**18
MOD = 1000000007
ri = lambda : int(input())
rs = lambda : input().strip()
rl = lambda : list(map(int, input().split()))

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.rnk = [0]*(n+1)

    # ノードxのrootノードを見つける
    def find(self, x):
        if(self.root[x] < 0):
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if(x == y):
            return 
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def same(self, x, y):
        return self.find(x) == self.find(y)
    # ノードxが属する木のサイズを返す
    def size(self, x):
        return -self.root[self.find(x)]


n = ri()
d=[tuple(rl())+tuple((i,)) for i in range(n)]

d.sort(key=lambda x: x[0])
edge=[]
for i in range(n-1):
    edge.append((d[i+1][2], d[i][2],d[i+1][0]-d[i][0]))
d.sort(key=lambda x:x[1])
for i in range(n-1):
    edge.append((d[i+1][2], d[i][2],d[i+1][1]-d[i][1]))
edge.sort(key=lambda x: x[2])
res=0
uf = UnionFind(n)
for e in edge:
    if uf.same(e[0], e[1]):
        continue
    uf.unite(e[0], e[1])
    res+=e[2]
print(res)

Submission status: Runtime Error

Solution code:
###ncrのmodあまりの話
mod=10**9+7
N=100005
kaidan=[1 for i in range(N)]
gyaku=[1 for i in range(N)]
for i in range(1,N):
    kaidan[i] = (i * kaidan[i-1])%mod
    gyaku[i]=pow(bikkuri[i], mod-2, mod)
def comb(a,b):
    return kaidan[a]*gyaku[b]*gyaku[a-b]
n,m=map(int,input().split())
if abs(n-m)>=2:
    print(0)
else:
    if n==m:
        print(kaidan[n]*kaidan[n]*2%mod)
    else:
        a=max(n,m)
        b=min(n,m)
        print(kaidan[a]*kaidan[b]%mod)

Submission status: Runtime Error

Solution code:
import sys
from functools import reduce,lru_cache
from operator import mul

def main():
  sys.setrecursionlimit(10 ** 5)
  N,M = map(int,input().split())
  
  @lru_cache(maxsize = None)
  def recur(n):
    if n == 0:
      return 1
    else:
      m = n * recur(n - 1)
      return m
      
  if N == M:
    L = [i for i in range(1,N + 1)]
    #ans = (reduce(mul,L) ** 2) * 2  % (10 ** 9 + 7)
    ans = (recur(N) % (10 ** 9 + 7))
    print(ans)
  elif abs(M - N) == 1: 
    ans = 1
    ans *= (recur(N) % (10 ** 9 + 7)) 
    ans *= (recur(M) % (10 ** 9 + 7))
    print(ans)
    
  else:
    print(0)
    
main()

Submission status: Runtime Error

Solution code:
[].pop()

Submission status: Runtime Error

Solution code:
# ARC076C - Reconciled?
def factorial_mod(x):
    MOD = 10 ** 9 + 7
    ret = 1
    for i in range(1, x + 1):
        ret = (ret * i) % MOD
    return ret


n, m = list(map(int, input().rstrip().split()))
MOD = 10 ** 9 + 7
n, m = min(n, m), max(n, m)
dif = m - n
if dif > 1:  # must be ...DDM...
    print(0)
else:
    if dif == 0:  # start with either D or M (DM..., MD...)
        ans = (factorial_mod(n) ** 2 * 2) % MOD
    else:  # sandwich (DMD or MDM)
        ans = (factorial(n) ** 2 * m) % MOD
print(ans)

Submission status: Runtime Error

Solution code:
# ARC076C - Reconciled?
def factorial_mod(x):
    MOD = 10 ** 9 + 7
    ret = 1
    for i in range(1, x + 1):
        ret = (ret * i) % MOD
    return ret


def main():
    n, m = list(map(int, input().rstrip().split()))
    MOD = 10 ** 9 + 7
    n, m = min(n, m), max(n, m)
    dif = m - n
    if dif > 1:  # must be ...DDM...
        print(0)
    else:
        if dif == 0:  # start with either D or M (DM..., MD...)
            ans = (factorial_mod(n) ** 2 * 2) % MOD
        else:  # sandwich (DMD or MDM)
            ans = (factorial(n) ** 2 * m) % MOD
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
# ARC076C - Reconciled?
def factorial_mod(x):
    MOD = 10 ** 9 + 7
    ret = 1
    for i in range(1, x + 1):
        ret = (ret * i) % MOD
    return ret


def main():
    n, m = list(map(int, input().rstrip().split()))
    MOD = 10 ** 9 + 7
    dif = abs(n - m)
    if dif > 1:  # must be ...DDM...
        print(0)
    else:
        if dif == 0:  # start with either D or M (DM..., MD...)
            ans = (factorial_mod(n) * factorial_mod(m) * 2) % MOD
        else:  # sandwich (DMD or MDM)
            ans = (factorial(n) * factorial(m)) % MOD
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
class UnionFind(object):
    def __init__(self, size):
        self.parent = [i for i in range(size)]
        self.rank = [0 for _ in range(size)]


    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            return self.find(self.parent[x])


    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.parent[x] = y
        else:
            self.parent[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def same(self, x, y):
        return self.find(x) == self.find(y)
def compute_mst_kruskal(N, edges):#N = 頂点数、edges 0-indexed
    edges = sorted(edges, key = lambda x:x[2])
    UF = UnionFind(N)
    cost = 0
    for edge in edges:
        x, y, w = edge
        if not UF.same(x, y):
            UF.unite(x, y)
            cost+=w
    return cost
N = int(input())
ixy = []
for i in range(N):
    x, y = map(int, input().split())
    ixy.append((i, x, y))
xy_x = sorted(ixy, key = lambda x:x[1])
xy_y = sorted(ixy, key = lambda x:x[2])
edges = []
for i in range(N-1):
    i1, x1, y1 = xy_x[i]
    i2, x2, y2 = xy_x[i+1]
    edges.append((i1, i2, x2-x1))
    i1, x1, y1 = xy_y[i]
    i2, x2, y2 = xy_y[i+1]
    edges.append((i1, i2, y2-y1))
ans = compute_mst_kruskal(N, edges)
print(ans)

Submission status: Runtime Error

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

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


def factorial(x):
  pie=x
  for i in range(1,x):
    pie*=i
  return pie

result=factorial(m)*factorial(n)
if m==n:
  result*=2

print(result)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
from operator import itemgetter

class UnionFind():
	def __init__(self, size):
		self.table = [-1 for _ in range(size)]

	def find(self, x):
		while self.table[x] >= 0:
			x = self.table[x]
		return x

	def union(self, x, y):
		s1 = self.find(x)
		s2 = self.find(y)
		if s1 != s2:
			if self.table[s1] > self.table[s2]:
				self.table[s2] = s1
			elif self.table[s1] < self.table[s2]:
				self.table[s1] = s2
			else:
				self.table[s1] = s2
				self.table[s2] -= 1
		return

n = int(input())
xy = [list(map(int, input().split())) for _ in range(n)]
xy_x = {i: xy[i][0] for i in range(n)}
xy_y = {i: xy[i][1] for i in range(n)}

v_x = sorted(xy_x.items(), key=itemgetter(1))
v_y = sorted(xy_y.items(), key=itemgetter(1))

edges = dict()

for i in range(n - 1):
	edges[(v_x[i][0], v_x[i+1][0])] = v_x[i+1][1] - v_x[i][1]
	edges[(v_y[i][0], v_y[i+1][0])] = v_y[i+1][1] - v_y[i][1]

uf = UnionFind(n)

edges = sorted(edges.items(), key=itemgetter(1))

ans = 0

while edges != list():
	e = edges.pop(0)
	if uf.find(e[0][0]) != uf.find(e[0][1]):
		uf.union(e[0][0], e[0][1])
		ans += e[1]

print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from heapq import heappop, heappush
def inpl(): return map(int, input().split())
N = int(input())

X = []
Y = []

for i in range(N):
    x, y = inpl()
    X.append((i, x))
    Y.append((i, y))

X = sorted(X, key=lambda x: x[1])
Y = sorted(Y, key=lambda y: y[1])

G = [[] for _ in range(N)]
for i in range(N-1):
    Xa, Xb = X[i], X[i+1]
    Ya, Yb = Y[i], Y[i+1]
    G[Xa[0]].append([Xb[0], Xb[1]-Xa[1]])
    G[Xb[0]].append([Xa[0], Xb[1]-Xa[1]])
    
    G[Ya[0]].append([Yb[0], Yb[1]-Ya[1]])
    G[Yb[0]].append([Ya[0], Yb[1]-Ya[1]])

visited = [False]*N
Q = [(0, 0)]
ans = 0

while Q:
    c, n = heappop(Q)
    if visited[n]:
        continue
    visited[n] = True
    ans += c
    
    for m, d in G[n]:
        if visited[m]:
            continue
        else:
            heappush(Q, (d, m))

print(ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt, gcd, factorial
from collections import deque
from bisect import bisect, bisect_left, bisect_right
INF = 10 ** 10
MOD = 10 ** 9 + 7

def main():
    N, M = map(int, input().split())
    diff = abs(N - M)
    if diff > 1:
        print(0)
        return

    ans = 2 if diff == 0 else 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)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n,m=map(int,raw_input())
mul1=mul2=1
if abs(n-m)>1:
    print 0
else:
    for i in range(1,n+1):
        mul1*=i
        mul1%=mod
    for i in range(1,m+1):
        mul2*=i
        mul2%=mod
    if n==m:
        print (2*mul1*mul2)%mod
    else:
        print (mul1*mul2)%mod

Submission status: Runtime Error

Solution code:
N, M = (int(i) for i in input().split())
ans = 1

# N = 100000                                                                                                                                                                                                                                                                          
# M = 100000                                                                                                                                                                                                                                                                          

if __name__ == '__main__':
    if N == (M + 1) or N == (M - 1):
        for n in range(1, N+1):
            ans *= n
            ans %= 1e9 + 7
        for m in range(1, M+1):
            ans *= m
            ans %= 1e9 + 7
    elif N == M:
        for n in range(1, N+1):
            ans *= n
            ans %= 1e9 + 7
        for m in range(1, M+1):
            ans *= m
            ans %= 1e9 + 7
        ans *= 2
        ans %= 1e9 + 7
    else:
        ans = 0

    print int(ans)

Submission status: Runtime Error

Solution code:
N, M = (int(i) for i in input().split())
ans = 1

if N == (M + 1) or N == (M - 1):
    for n in range(1, N+1):
        ans *= n
        ans %= 1e9 + 7
    for m in range(1, M+1):
        ans *= m
        ans %= 1e9 + 7
elif N == M:
    for n in range(1, N+1):
        ans *= n
        ans %= 1e9 + 7
    for m in range(1, M+1):
        ans *= m
        ans %= 1e9 + 7
    ans *= 2
    ans %= 1e9 + 7
else:
    ans = 0

print int(ans)

Submission status: Runtime Error

Solution code:
l = input().split()
N = l[0]
M = l[1]
ans = 1

# N = 100000                                                                                                                                                                                                                                                                          
# M = 100000                                                                                                                                                                                                                                                                          

if N == (M + 1) or N == (M - 1):
    for n in range(1, N+1):
        ans *= n
        ans %= 1e9 + 7
    for m in range(1, M+1):
        ans *= m
        ans %= 1e9 + 7
elif N == M:
    for n in range(1, N+1):
        ans *= n
        ans %= 1e9 + 7
    for m in range(1, M+1):
        ans *= m
        ans %= 1e9 + 7
    ans *= 2
    ans %= 1e9 + 7
else:
    ans = 0

print int(ans)

Submission status: Runtime Error

Solution code:
l = raw_input().split()
N = l[0]
M = l[1]
ans = 1                                                                                                                                                                                                                                                               

if N == (M + 1) or N == (M - 1):
    for n in range(1, N+1):
        ans *= n
        ans %= 1e9 + 7
    for m in range(1, M+1):
        ans *= m
        ans %= 1e9 + 7
elif N == M:
    for n in range(1, N+1):
        ans *= n
        ans %= 1e9 + 7
    for m in range(1, M+1):
        ans *= m
        ans %= 1e9 + 7
    ans *= 2
    ans %= 1e9 + 7
else:
    ans = 0

print int(ans)

Submission status: Runtime Error

Solution code:
# coding:utf-8

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

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

# 引数として、nかmのうちの小さい方の数字を受け取る
def count(n,m):
    return kaijo(n)*kaijo(m)

if n-m==-1 or n-m==1:
    result=count(n,m)
    amari=result%(10**9+7)
    print amari
elif n-m==0:
    result=count(n,m)
    result*=2
    amari=result%(10**9+7)
    print amari
else:
    print "0"

Submission status: Runtime Error

Solution code:
# coding:utf-8

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

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

# 引数として、nかmのうちの小さい方の数字を受け取る
def count(n,m):
    return kaijo(n)*kaijo(m)

if n-m==-1 or n-m==1:
    result=count(n,m)
    print result
elif n-m==0:
    result=count(n,m)
    result*=2
    print result
else:
    print "0"

Submission status: Runtime Error

Solution code:
# coding:utf-8

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

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

# 引数として、nかmのうちの小さい方の数字を受け取る
def count(n,m):
    print kaijo(n)*kaijo(m)

if n-m==-1 or n-m==1:
    count=count(n,m)
elif n-m==0:
    count=count(n,m)
    count*=2
else:
    print "0"

Submission status: Runtime Error

Solution code:
#!/usr/bin/python
# coding: UTF-8

import itertools

dog = input()
mon = input()

n = dog + mon

list_d = ["0"] * dog
list_m = ["1"] * mon

list_d.extend(list_m)

p = list(itertools.permutations(list_d))

ans = 0
length = len(p)

print length

for i in range(length):
    for j in range(len(p[i]) - 1):
        if p[i][j] == p[i][j + 1]:
            break
        if j == len(p[i]) - 2:
            ans += 1

print ans

Submission status: Runtime Error

Solution code:
R, C, N = map(int, raw_input().split())

lines = []
for i in range(N):
	x, y, xx, yy = map(int, raw_input().split())
	if (x in [0, R] or y in [0, C]) and (xx in [0, R] or yy in [0, C]):
		if x <= y:
			first = x+y
		else:
			first = (R*2 + C*2)-(x+y)
		if xx <= yy:
			second = xx+yy
		else:
			second = (R*2 + C*2)-(xx+yy)
		new_line = [first, second] if first < second else [second, first]
		j = 0
		for j in range(len(lines)):
			if new_line[0] < lines[j][0]:
				lines.insert(j, new_line)
				break
		else:
			lines.append(new_line)

false_flag = False
scopes = []
scopes.append(lines.pop(0))
while lines and not false_flag:
	while scopes:
		next_scope = lines.pop(0)
		right = scopes[-1][1]
		next_left = next_scope[0]
		next_right = next_scope[1]
		if next_left < right:
			if next_right < right:
				if lines:
					scopes.append(next_scope)
				else:
					break
			else:
				false_flag = True
				break
		else:
			scopes.pop()
	else:
		scopes.append(next_scope)

if false_flag:
	print 'NO'
else:
	print 'YES'

Submission status: Runtime Error

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

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

if abs(n-m)>1: ans=0
elif n==m: ans=fact(n)**2*2
else: ans=fact(n)*fact(m)

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

Submission status: Runtime Error

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

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

if abs(n-m)>1: ans=0
elif n==m: ans=(fact(n)%(10**9+7))**2*2
else: ans=(fact(n)%(10**9+7))*(fact(m)%(10**9+7))

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

Submission status: Runtime Error

Solution code:
import math as m

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

if abs(n-m)>1: ans=0
elif n==m: ans=m.factorial(n)**2*2
else: ans=m.factorial(n)*m.factorial(m)

print(ans)

Submission status: Runtime Error

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

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

if abs(n-m)>1: ans=0
elif n==m: ans=fact(n)**2*2
else: ans=fact(n)*fact(m)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000)

d = 10**9 + 7


def factorial(n):
    if (n > 1):
        return (n % d) * factorial(n - 1)
    return 1


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

if abs(n - m) <= 1:
    ans = (factorial(n) % d) * (factorial(m) % d)
    ans %= d
    if n == m:
        ans *= 2

    # ans %= d
    print(ans)

else:
    print(0)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from math import factorial

N = int(input())
cities = [[int(m) for m in input().split()] for n in range(N)]

def reasonable_way(A, B):
    A = list(sorted(set(A)))
    B = list(sorted(set(B)))
    
    a = 0
    b = 0
    
    cheap = 10**9 + 1
    
    while a < len(A) and b < len(B):
        if b+1 < len(B):
            while A[a] - B[b+1] > 0:
                if b+1 == len(B):
                    break
                else:
                    b += 1

        cheap = min(abs(A[a] - B[b]), cheap)
        if b+1 < len(B):
            cheap = min(abs(A[a] - B[b+1]), cheap)

        if cheap == 0:
            return 0

        a += 1        

    return cheap

x_key_map = {x: [] for x in set([city[0] for city in cities])}
y_key_map = {y: [] for y in set([city[1] for city in cities])}

for city in cities:
    x_key_map[city[0]].append(city[1])
    y_key_map[city[1]].append(city[1])

x_keys = list(sorted(x_key_map.keys()))
y_keys = list(sorted(y_key_map.keys()))
    
tmp = 0
for i in range(len(x_keys) - 1):
    tmp += min(abs(x_keys[i] - x_keys[i+1]),
               reasonable_way(x_key_map[x_keys[i]], x_key_map[x_keys[i+1]]))

result = tmp
tmp = 0

for i in range(len(y_keys) - 1):
    tmp += min(abs(y_keys[i] - y_keys[i+1]),
               reasonable_way(y_key_map[y_keys[i]], y_key_map[y_keys[i+1]]))    
result = min(result, tmp)

print(result)

Submission status: Runtime Error

Solution code:
# D
import numpy as np
N = int(input())
X = np.zeros(N, dtype=int)
Y = np.zeros(N, dtype=int)

for i in range(N):
    x, y = map(int, input().split())
    X[i] = x
    Y[i] = y

# edges
X_s = np.argsort(X)
Y_s = np.argsort(Y)

edge_list = []
edge_weight = []
for i in range(N-1):
    edge_list.append([X_s[i], X_s[i+1]])
    edge_weight.append(min(abs(X[X_s[i+1]] - X[X_s[i]]), abs(Y[X_s[i+1]] - Y[X_s[i]])))
    edge_list.append([Y_s[i], Y_s[i+1]])
    edge_weight.append(min(abs(X[Y_s[i+1]] - X[Y_s[i]]), abs(Y[Y_s[i+1]] - Y[Y_s[i]])))
    
# sort edges
sel = np.argsort(np.array(edge_weight))

res = 0
flg = np.zeros(N)

for s in sel:
    m, n = edge_list[s]
    if flg[m]*flg[n] > 0:
        pass
    else:
        res += edge_weight[s]
        flg[m] = 1
        flg[n] = 1
print(res)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000)

d = 10**9 + 7


def factorial(n):
    if (n > 1):
        return (n % d) * factorial(n-1)
    return 1


n, m = map(int, input().split())
ans = (factorial(n) % d) * (factorial(m) % d)
ans %= d
if n == m:
    ans *= 2

print(ans)

Submission status: Runtime Error

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


if abs(N - M) > 1:
    print(0)
elif N == M:
    res = math.factorial(N) * math.factorial(M) * 2
else:
    res = math.factorial(N) * math.factorial(M)

print(res % int(1e9 + 7))

Submission status: Runtime Error

Solution code:
def Factorial(integer) :
    global M

    product = 1
    if integer == 0 : return 1
    for num in range(1 ,integer + 1):
        product *= num
        product%=M
    return product


d=sorted(list(map(int,input().split(" "))))
M=10**9+7

if abs(d[0]-d[1])>1:
    res=0
elif d[0]==d[1]:

    res=((Factorial(d[0])%M)**2)*2
else:
    res=Factorial(d[1])*Factorialo(d[0])

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

Submission status: Runtime Error

Solution code:
def kaijo(x):
    if x>1:
        return x*kaijo(x-1)

    return 1



d=sorted(list(map(int,input().split(" "))))

if abs(d[0]-d[1])>1:
    res=0
elif d[0]==d[1]:

    res=(kaijo(d[0])**2)*2
else:
    res=kaijo(d[1])*kaijo(d[0])

print(res)

Submission status: Runtime Error

Solution code:
from math import factorial

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

def foo(N,M):
	if N == M+1 or N+1 == M:
		tm = factorial(min(N,M))
		return(tm*max(N,M)+tm)

	elif N==M:
		return(2*factorial(N)*2)

	else:
		return(0)

print(foo(N,M)/(10**9+7))